• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  *  Copyright 2008 The WebRTC Project Authors. All rights reserved.
3  *
4  *  Use of this source code is governed by a BSD-style license
5  *  that can be found in the LICENSE file in the root of the source
6  *  tree. An additional intellectual property rights grant can be found
7  *  in the file PATENTS.  All contributing project authors may
8  *  be found in the AUTHORS file in the root of the source tree.
9  */
10 
11 #if HAVE_OPENSSL_SSL_H
12 
13 #include "webrtc/base/openssladapter.h"
14 
15 #if defined(WEBRTC_POSIX)
16 #include <unistd.h>
17 #endif
18 
19 // Must be included first before openssl headers.
20 #include "webrtc/base/win32.h"  // NOLINT
21 
22 #include <openssl/bio.h>
23 #include <openssl/crypto.h>
24 #include <openssl/err.h>
25 #include <openssl/opensslv.h>
26 #include <openssl/rand.h>
27 #include <openssl/x509.h>
28 #include <openssl/x509v3.h>
29 
30 #if HAVE_CONFIG_H
31 #include "config.h"
32 #endif  // HAVE_CONFIG_H
33 
34 #include "webrtc/base/arraysize.h"
35 #include "webrtc/base/common.h"
36 #include "webrtc/base/logging.h"
37 #include "webrtc/base/openssl.h"
38 #include "webrtc/base/safe_conversions.h"
39 #include "webrtc/base/sslroots.h"
40 #include "webrtc/base/stringutils.h"
41 #include "webrtc/base/thread.h"
42 
43 #ifndef OPENSSL_IS_BORINGSSL
44 
45 // TODO: Use a nicer abstraction for mutex.
46 
47 #if defined(WEBRTC_WIN)
48   #define MUTEX_TYPE HANDLE
49   #define MUTEX_SETUP(x) (x) = CreateMutex(NULL, FALSE, NULL)
50   #define MUTEX_CLEANUP(x) CloseHandle(x)
51   #define MUTEX_LOCK(x) WaitForSingleObject((x), INFINITE)
52   #define MUTEX_UNLOCK(x) ReleaseMutex(x)
53   #define THREAD_ID GetCurrentThreadId()
54 #elif defined(WEBRTC_POSIX)
55   #define MUTEX_TYPE pthread_mutex_t
56   #define MUTEX_SETUP(x) pthread_mutex_init(&(x), NULL)
57   #define MUTEX_CLEANUP(x) pthread_mutex_destroy(&(x))
58   #define MUTEX_LOCK(x) pthread_mutex_lock(&(x))
59   #define MUTEX_UNLOCK(x) pthread_mutex_unlock(&(x))
60   #define THREAD_ID pthread_self()
61 #else
62   #error You must define mutex operations appropriate for your platform!
63 #endif
64 
65 struct CRYPTO_dynlock_value {
66   MUTEX_TYPE mutex;
67 };
68 
69 #endif  // #ifndef OPENSSL_IS_BORINGSSL
70 
71 //////////////////////////////////////////////////////////////////////
72 // SocketBIO
73 //////////////////////////////////////////////////////////////////////
74 
75 static int socket_write(BIO* h, const char* buf, int num);
76 static int socket_read(BIO* h, char* buf, int size);
77 static int socket_puts(BIO* h, const char* str);
78 static long socket_ctrl(BIO* h, int cmd, long arg1, void* arg2);
79 static int socket_new(BIO* h);
80 static int socket_free(BIO* data);
81 
82 // TODO(davidben): This should be const once BoringSSL is assumed.
83 static BIO_METHOD methods_socket = {
84   BIO_TYPE_BIO,
85   "socket",
86   socket_write,
87   socket_read,
88   socket_puts,
89   0,
90   socket_ctrl,
91   socket_new,
92   socket_free,
93   NULL,
94 };
95 
BIO_s_socket2()96 static BIO_METHOD* BIO_s_socket2() { return(&methods_socket); }
97 
BIO_new_socket(rtc::AsyncSocket * socket)98 static BIO* BIO_new_socket(rtc::AsyncSocket* socket) {
99   BIO* ret = BIO_new(BIO_s_socket2());
100   if (ret == NULL) {
101           return NULL;
102   }
103   ret->ptr = socket;
104   return ret;
105 }
106 
socket_new(BIO * b)107 static int socket_new(BIO* b) {
108   b->shutdown = 0;
109   b->init = 1;
110   b->num = 0; // 1 means socket closed
111   b->ptr = 0;
112   return 1;
113 }
114 
socket_free(BIO * b)115 static int socket_free(BIO* b) {
116   if (b == NULL)
117     return 0;
118   return 1;
119 }
120 
socket_read(BIO * b,char * out,int outl)121 static int socket_read(BIO* b, char* out, int outl) {
122   if (!out)
123     return -1;
124   rtc::AsyncSocket* socket = static_cast<rtc::AsyncSocket*>(b->ptr);
125   BIO_clear_retry_flags(b);
126   int result = socket->Recv(out, outl);
127   if (result > 0) {
128     return result;
129   } else if (result == 0) {
130     b->num = 1;
131   } else if (socket->IsBlocking()) {
132     BIO_set_retry_read(b);
133   }
134   return -1;
135 }
136 
socket_write(BIO * b,const char * in,int inl)137 static int socket_write(BIO* b, const char* in, int inl) {
138   if (!in)
139     return -1;
140   rtc::AsyncSocket* socket = static_cast<rtc::AsyncSocket*>(b->ptr);
141   BIO_clear_retry_flags(b);
142   int result = socket->Send(in, inl);
143   if (result > 0) {
144     return result;
145   } else if (socket->IsBlocking()) {
146     BIO_set_retry_write(b);
147   }
148   return -1;
149 }
150 
socket_puts(BIO * b,const char * str)151 static int socket_puts(BIO* b, const char* str) {
152   return socket_write(b, str, rtc::checked_cast<int>(strlen(str)));
153 }
154 
socket_ctrl(BIO * b,int cmd,long num,void * ptr)155 static long socket_ctrl(BIO* b, int cmd, long num, void* ptr) {
156   RTC_UNUSED(num);
157   RTC_UNUSED(ptr);
158 
159   switch (cmd) {
160   case BIO_CTRL_RESET:
161     return 0;
162   case BIO_CTRL_EOF:
163     return b->num;
164   case BIO_CTRL_WPENDING:
165   case BIO_CTRL_PENDING:
166     return 0;
167   case BIO_CTRL_FLUSH:
168     return 1;
169   default:
170     return 0;
171   }
172 }
173 
174 /////////////////////////////////////////////////////////////////////////////
175 // OpenSSLAdapter
176 /////////////////////////////////////////////////////////////////////////////
177 
178 namespace rtc {
179 
180 #ifndef OPENSSL_IS_BORINGSSL
181 
182 // This array will store all of the mutexes available to OpenSSL.
183 static MUTEX_TYPE* mutex_buf = NULL;
184 
locking_function(int mode,int n,const char * file,int line)185 static void locking_function(int mode, int n, const char * file, int line) {
186   if (mode & CRYPTO_LOCK) {
187     MUTEX_LOCK(mutex_buf[n]);
188   } else {
189     MUTEX_UNLOCK(mutex_buf[n]);
190   }
191 }
192 
id_function()193 static unsigned long id_function() {  // NOLINT
194   // Use old-style C cast because THREAD_ID's type varies with the platform,
195   // in some cases requiring static_cast, and in others requiring
196   // reinterpret_cast.
197   return (unsigned long)THREAD_ID; // NOLINT
198 }
199 
dyn_create_function(const char * file,int line)200 static CRYPTO_dynlock_value* dyn_create_function(const char* file, int line) {
201   CRYPTO_dynlock_value* value = new CRYPTO_dynlock_value;
202   if (!value)
203     return NULL;
204   MUTEX_SETUP(value->mutex);
205   return value;
206 }
207 
dyn_lock_function(int mode,CRYPTO_dynlock_value * l,const char * file,int line)208 static void dyn_lock_function(int mode, CRYPTO_dynlock_value* l,
209                               const char* file, int line) {
210   if (mode & CRYPTO_LOCK) {
211     MUTEX_LOCK(l->mutex);
212   } else {
213     MUTEX_UNLOCK(l->mutex);
214   }
215 }
216 
dyn_destroy_function(CRYPTO_dynlock_value * l,const char * file,int line)217 static void dyn_destroy_function(CRYPTO_dynlock_value* l,
218                                  const char* file, int line) {
219   MUTEX_CLEANUP(l->mutex);
220   delete l;
221 }
222 
223 #endif  // #ifndef OPENSSL_IS_BORINGSSL
224 
225 VerificationCallback OpenSSLAdapter::custom_verify_callback_ = NULL;
226 
InitializeSSL(VerificationCallback callback)227 bool OpenSSLAdapter::InitializeSSL(VerificationCallback callback) {
228   if (!InitializeSSLThread() || !SSL_library_init())
229       return false;
230 #if !defined(ADDRESS_SANITIZER) || !defined(WEBRTC_MAC) || defined(WEBRTC_IOS)
231   // Loading the error strings crashes mac_asan.  Omit this debugging aid there.
232   SSL_load_error_strings();
233 #endif
234   ERR_load_BIO_strings();
235   OpenSSL_add_all_algorithms();
236   RAND_poll();
237   custom_verify_callback_ = callback;
238   return true;
239 }
240 
InitializeSSLThread()241 bool OpenSSLAdapter::InitializeSSLThread() {
242   // BoringSSL is doing the locking internally, so the callbacks are not used
243   // in this case (and are no-ops anyways).
244 #ifndef OPENSSL_IS_BORINGSSL
245   mutex_buf = new MUTEX_TYPE[CRYPTO_num_locks()];
246   if (!mutex_buf)
247     return false;
248   for (int i = 0; i < CRYPTO_num_locks(); ++i)
249     MUTEX_SETUP(mutex_buf[i]);
250 
251   // we need to cast our id_function to return an unsigned long -- pthread_t is
252   // a pointer
253   CRYPTO_set_id_callback(id_function);
254   CRYPTO_set_locking_callback(locking_function);
255   CRYPTO_set_dynlock_create_callback(dyn_create_function);
256   CRYPTO_set_dynlock_lock_callback(dyn_lock_function);
257   CRYPTO_set_dynlock_destroy_callback(dyn_destroy_function);
258 #endif  // #ifndef OPENSSL_IS_BORINGSSL
259   return true;
260 }
261 
CleanupSSL()262 bool OpenSSLAdapter::CleanupSSL() {
263 #ifndef OPENSSL_IS_BORINGSSL
264   if (!mutex_buf)
265     return false;
266   CRYPTO_set_id_callback(NULL);
267   CRYPTO_set_locking_callback(NULL);
268   CRYPTO_set_dynlock_create_callback(NULL);
269   CRYPTO_set_dynlock_lock_callback(NULL);
270   CRYPTO_set_dynlock_destroy_callback(NULL);
271   for (int i = 0; i < CRYPTO_num_locks(); ++i)
272     MUTEX_CLEANUP(mutex_buf[i]);
273   delete [] mutex_buf;
274   mutex_buf = NULL;
275 #endif  // #ifndef OPENSSL_IS_BORINGSSL
276   return true;
277 }
278 
OpenSSLAdapter(AsyncSocket * socket)279 OpenSSLAdapter::OpenSSLAdapter(AsyncSocket* socket)
280   : SSLAdapter(socket),
281     state_(SSL_NONE),
282     ssl_read_needs_write_(false),
283     ssl_write_needs_read_(false),
284     restartable_(false),
285     ssl_(NULL), ssl_ctx_(NULL),
286     ssl_mode_(SSL_MODE_TLS),
287     custom_verification_succeeded_(false) {
288 }
289 
~OpenSSLAdapter()290 OpenSSLAdapter::~OpenSSLAdapter() {
291   Cleanup();
292 }
293 
294 void
SetMode(SSLMode mode)295 OpenSSLAdapter::SetMode(SSLMode mode) {
296   ASSERT(state_ == SSL_NONE);
297   ssl_mode_ = mode;
298 }
299 
300 int
StartSSL(const char * hostname,bool restartable)301 OpenSSLAdapter::StartSSL(const char* hostname, bool restartable) {
302   if (state_ != SSL_NONE)
303     return -1;
304 
305   ssl_host_name_ = hostname;
306   restartable_ = restartable;
307 
308   if (socket_->GetState() != Socket::CS_CONNECTED) {
309     state_ = SSL_WAIT;
310     return 0;
311   }
312 
313   state_ = SSL_CONNECTING;
314   if (int err = BeginSSL()) {
315     Error("BeginSSL", err, false);
316     return err;
317   }
318 
319   return 0;
320 }
321 
322 int
BeginSSL()323 OpenSSLAdapter::BeginSSL() {
324   LOG(LS_INFO) << "BeginSSL: " << ssl_host_name_;
325   ASSERT(state_ == SSL_CONNECTING);
326 
327   int err = 0;
328   BIO* bio = NULL;
329 
330   // First set up the context
331   if (!ssl_ctx_)
332     ssl_ctx_ = SetupSSLContext();
333 
334   if (!ssl_ctx_) {
335     err = -1;
336     goto ssl_error;
337   }
338 
339   bio = BIO_new_socket(static_cast<AsyncSocketAdapter*>(socket_));
340   if (!bio) {
341     err = -1;
342     goto ssl_error;
343   }
344 
345   ssl_ = SSL_new(ssl_ctx_);
346   if (!ssl_) {
347     err = -1;
348     goto ssl_error;
349   }
350 
351   SSL_set_app_data(ssl_, this);
352 
353   SSL_set_bio(ssl_, bio, bio);
354   SSL_set_mode(ssl_, SSL_MODE_ENABLE_PARTIAL_WRITE |
355                      SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
356 
357   // the SSL object owns the bio now
358   bio = NULL;
359 
360   // Do the connect
361   err = ContinueSSL();
362   if (err != 0)
363     goto ssl_error;
364 
365   return err;
366 
367 ssl_error:
368   Cleanup();
369   if (bio)
370     BIO_free(bio);
371 
372   return err;
373 }
374 
375 int
ContinueSSL()376 OpenSSLAdapter::ContinueSSL() {
377   ASSERT(state_ == SSL_CONNECTING);
378 
379   // Clear the DTLS timer
380   Thread::Current()->Clear(this, MSG_TIMEOUT);
381 
382   int code = SSL_connect(ssl_);
383   switch (SSL_get_error(ssl_, code)) {
384   case SSL_ERROR_NONE:
385     if (!SSLPostConnectionCheck(ssl_, ssl_host_name_.c_str())) {
386       LOG(LS_ERROR) << "TLS post connection check failed";
387       // make sure we close the socket
388       Cleanup();
389       // The connect failed so return -1 to shut down the socket
390       return -1;
391     }
392 
393     state_ = SSL_CONNECTED;
394     AsyncSocketAdapter::OnConnectEvent(this);
395 #if 0  // TODO: worry about this
396     // Don't let ourselves go away during the callbacks
397     PRefPtr<OpenSSLAdapter> lock(this);
398     LOG(LS_INFO) << " -- onStreamReadable";
399     AsyncSocketAdapter::OnReadEvent(this);
400     LOG(LS_INFO) << " -- onStreamWriteable";
401     AsyncSocketAdapter::OnWriteEvent(this);
402 #endif
403     break;
404 
405   case SSL_ERROR_WANT_READ:
406     LOG(LS_VERBOSE) << " -- error want read";
407     struct timeval timeout;
408     if (DTLSv1_get_timeout(ssl_, &timeout)) {
409       int delay = timeout.tv_sec * 1000 + timeout.tv_usec/1000;
410 
411       Thread::Current()->PostDelayed(delay, this, MSG_TIMEOUT, 0);
412     }
413     break;
414 
415   case SSL_ERROR_WANT_WRITE:
416     break;
417 
418   case SSL_ERROR_ZERO_RETURN:
419   default:
420     LOG(LS_WARNING) << "ContinueSSL -- error " << code;
421     return (code != 0) ? code : -1;
422   }
423 
424   return 0;
425 }
426 
427 void
Error(const char * context,int err,bool signal)428 OpenSSLAdapter::Error(const char* context, int err, bool signal) {
429   LOG(LS_WARNING) << "OpenSSLAdapter::Error("
430                   << context << ", " << err << ")";
431   state_ = SSL_ERROR;
432   SetError(err);
433   if (signal)
434     AsyncSocketAdapter::OnCloseEvent(this, err);
435 }
436 
437 void
Cleanup()438 OpenSSLAdapter::Cleanup() {
439   LOG(LS_INFO) << "Cleanup";
440 
441   state_ = SSL_NONE;
442   ssl_read_needs_write_ = false;
443   ssl_write_needs_read_ = false;
444   custom_verification_succeeded_ = false;
445 
446   if (ssl_) {
447     SSL_free(ssl_);
448     ssl_ = NULL;
449   }
450 
451   if (ssl_ctx_) {
452     SSL_CTX_free(ssl_ctx_);
453     ssl_ctx_ = NULL;
454   }
455 
456   // Clear the DTLS timer
457   Thread::Current()->Clear(this, MSG_TIMEOUT);
458 }
459 
460 //
461 // AsyncSocket Implementation
462 //
463 
464 int
Send(const void * pv,size_t cb)465 OpenSSLAdapter::Send(const void* pv, size_t cb) {
466   //LOG(LS_INFO) << "OpenSSLAdapter::Send(" << cb << ")";
467 
468   switch (state_) {
469   case SSL_NONE:
470     return AsyncSocketAdapter::Send(pv, cb);
471 
472   case SSL_WAIT:
473   case SSL_CONNECTING:
474     SetError(EWOULDBLOCK);
475     return SOCKET_ERROR;
476 
477   case SSL_CONNECTED:
478     break;
479 
480   case SSL_ERROR:
481   default:
482     return SOCKET_ERROR;
483   }
484 
485   // OpenSSL will return an error if we try to write zero bytes
486   if (cb == 0)
487     return 0;
488 
489   ssl_write_needs_read_ = false;
490 
491   int code = SSL_write(ssl_, pv, checked_cast<int>(cb));
492   switch (SSL_get_error(ssl_, code)) {
493   case SSL_ERROR_NONE:
494     //LOG(LS_INFO) << " -- success";
495     return code;
496   case SSL_ERROR_WANT_READ:
497     //LOG(LS_INFO) << " -- error want read";
498     ssl_write_needs_read_ = true;
499     SetError(EWOULDBLOCK);
500     break;
501   case SSL_ERROR_WANT_WRITE:
502     //LOG(LS_INFO) << " -- error want write";
503     SetError(EWOULDBLOCK);
504     break;
505   case SSL_ERROR_ZERO_RETURN:
506     //LOG(LS_INFO) << " -- remote side closed";
507     SetError(EWOULDBLOCK);
508     // do we need to signal closure?
509     break;
510   default:
511     //LOG(LS_INFO) << " -- error " << code;
512     Error("SSL_write", (code ? code : -1), false);
513     break;
514   }
515 
516   return SOCKET_ERROR;
517 }
518 
519 int
SendTo(const void * pv,size_t cb,const SocketAddress & addr)520 OpenSSLAdapter::SendTo(const void* pv, size_t cb, const SocketAddress& addr) {
521   if (socket_->GetState() == Socket::CS_CONNECTED &&
522       addr == socket_->GetRemoteAddress()) {
523     return Send(pv, cb);
524   }
525 
526   SetError(ENOTCONN);
527 
528   return SOCKET_ERROR;
529 }
530 
531 int
Recv(void * pv,size_t cb)532 OpenSSLAdapter::Recv(void* pv, size_t cb) {
533   //LOG(LS_INFO) << "OpenSSLAdapter::Recv(" << cb << ")";
534   switch (state_) {
535 
536   case SSL_NONE:
537     return AsyncSocketAdapter::Recv(pv, cb);
538 
539   case SSL_WAIT:
540   case SSL_CONNECTING:
541     SetError(EWOULDBLOCK);
542     return SOCKET_ERROR;
543 
544   case SSL_CONNECTED:
545     break;
546 
547   case SSL_ERROR:
548   default:
549     return SOCKET_ERROR;
550   }
551 
552   // Don't trust OpenSSL with zero byte reads
553   if (cb == 0)
554     return 0;
555 
556   ssl_read_needs_write_ = false;
557 
558   int code = SSL_read(ssl_, pv, checked_cast<int>(cb));
559   switch (SSL_get_error(ssl_, code)) {
560   case SSL_ERROR_NONE:
561     //LOG(LS_INFO) << " -- success";
562     return code;
563   case SSL_ERROR_WANT_READ:
564     //LOG(LS_INFO) << " -- error want read";
565     SetError(EWOULDBLOCK);
566     break;
567   case SSL_ERROR_WANT_WRITE:
568     //LOG(LS_INFO) << " -- error want write";
569     ssl_read_needs_write_ = true;
570     SetError(EWOULDBLOCK);
571     break;
572   case SSL_ERROR_ZERO_RETURN:
573     //LOG(LS_INFO) << " -- remote side closed";
574     SetError(EWOULDBLOCK);
575     // do we need to signal closure?
576     break;
577   default:
578     //LOG(LS_INFO) << " -- error " << code;
579     Error("SSL_read", (code ? code : -1), false);
580     break;
581   }
582 
583   return SOCKET_ERROR;
584 }
585 
586 int
RecvFrom(void * pv,size_t cb,SocketAddress * paddr)587 OpenSSLAdapter::RecvFrom(void* pv, size_t cb, SocketAddress* paddr) {
588   if (socket_->GetState() == Socket::CS_CONNECTED) {
589     int ret = Recv(pv, cb);
590 
591     *paddr = GetRemoteAddress();
592 
593     return ret;
594   }
595 
596   SetError(ENOTCONN);
597 
598   return SOCKET_ERROR;
599 }
600 
601 int
Close()602 OpenSSLAdapter::Close() {
603   Cleanup();
604   state_ = restartable_ ? SSL_WAIT : SSL_NONE;
605   return AsyncSocketAdapter::Close();
606 }
607 
608 Socket::ConnState
GetState() const609 OpenSSLAdapter::GetState() const {
610   //if (signal_close_)
611   //  return CS_CONNECTED;
612   ConnState state = socket_->GetState();
613   if ((state == CS_CONNECTED)
614       && ((state_ == SSL_WAIT) || (state_ == SSL_CONNECTING)))
615     state = CS_CONNECTING;
616   return state;
617 }
618 
619 void
OnMessage(Message * msg)620 OpenSSLAdapter::OnMessage(Message* msg) {
621   if (MSG_TIMEOUT == msg->message_id) {
622     LOG(LS_INFO) << "DTLS timeout expired";
623     DTLSv1_handle_timeout(ssl_);
624     ContinueSSL();
625   }
626 }
627 
628 void
OnConnectEvent(AsyncSocket * socket)629 OpenSSLAdapter::OnConnectEvent(AsyncSocket* socket) {
630   LOG(LS_INFO) << "OpenSSLAdapter::OnConnectEvent";
631   if (state_ != SSL_WAIT) {
632     ASSERT(state_ == SSL_NONE);
633     AsyncSocketAdapter::OnConnectEvent(socket);
634     return;
635   }
636 
637   state_ = SSL_CONNECTING;
638   if (int err = BeginSSL()) {
639     AsyncSocketAdapter::OnCloseEvent(socket, err);
640   }
641 }
642 
643 void
OnReadEvent(AsyncSocket * socket)644 OpenSSLAdapter::OnReadEvent(AsyncSocket* socket) {
645   //LOG(LS_INFO) << "OpenSSLAdapter::OnReadEvent";
646 
647   if (state_ == SSL_NONE) {
648     AsyncSocketAdapter::OnReadEvent(socket);
649     return;
650   }
651 
652   if (state_ == SSL_CONNECTING) {
653     if (int err = ContinueSSL()) {
654       Error("ContinueSSL", err);
655     }
656     return;
657   }
658 
659   if (state_ != SSL_CONNECTED)
660     return;
661 
662   // Don't let ourselves go away during the callbacks
663   //PRefPtr<OpenSSLAdapter> lock(this); // TODO: fix this
664   if (ssl_write_needs_read_)  {
665     //LOG(LS_INFO) << " -- onStreamWriteable";
666     AsyncSocketAdapter::OnWriteEvent(socket);
667   }
668 
669   //LOG(LS_INFO) << " -- onStreamReadable";
670   AsyncSocketAdapter::OnReadEvent(socket);
671 }
672 
673 void
OnWriteEvent(AsyncSocket * socket)674 OpenSSLAdapter::OnWriteEvent(AsyncSocket* socket) {
675   //LOG(LS_INFO) << "OpenSSLAdapter::OnWriteEvent";
676 
677   if (state_ == SSL_NONE) {
678     AsyncSocketAdapter::OnWriteEvent(socket);
679     return;
680   }
681 
682   if (state_ == SSL_CONNECTING) {
683     if (int err = ContinueSSL()) {
684       Error("ContinueSSL", err);
685     }
686     return;
687   }
688 
689   if (state_ != SSL_CONNECTED)
690     return;
691 
692   // Don't let ourselves go away during the callbacks
693   //PRefPtr<OpenSSLAdapter> lock(this); // TODO: fix this
694 
695   if (ssl_read_needs_write_)  {
696     //LOG(LS_INFO) << " -- onStreamReadable";
697     AsyncSocketAdapter::OnReadEvent(socket);
698   }
699 
700   //LOG(LS_INFO) << " -- onStreamWriteable";
701   AsyncSocketAdapter::OnWriteEvent(socket);
702 }
703 
704 void
OnCloseEvent(AsyncSocket * socket,int err)705 OpenSSLAdapter::OnCloseEvent(AsyncSocket* socket, int err) {
706   LOG(LS_INFO) << "OpenSSLAdapter::OnCloseEvent(" << err << ")";
707   AsyncSocketAdapter::OnCloseEvent(socket, err);
708 }
709 
710 // This code is taken from the "Network Security with OpenSSL"
711 // sample in chapter 5
712 
VerifyServerName(SSL * ssl,const char * host,bool ignore_bad_cert)713 bool OpenSSLAdapter::VerifyServerName(SSL* ssl, const char* host,
714                                       bool ignore_bad_cert) {
715   if (!host)
716     return false;
717 
718   // Checking the return from SSL_get_peer_certificate here is not strictly
719   // necessary.  With our setup, it is not possible for it to return
720   // NULL.  However, it is good form to check the return.
721   X509* certificate = SSL_get_peer_certificate(ssl);
722   if (!certificate)
723     return false;
724 
725   // Logging certificates is extremely verbose. So it is disabled by default.
726 #ifdef LOG_CERTIFICATES
727   {
728     LOG(LS_INFO) << "Certificate from server:";
729     BIO* mem = BIO_new(BIO_s_mem());
730     X509_print_ex(mem, certificate, XN_FLAG_SEP_CPLUS_SPC, X509_FLAG_NO_HEADER);
731     BIO_write(mem, "\0", 1);
732     char* buffer;
733     BIO_get_mem_data(mem, &buffer);
734     LOG(LS_INFO) << buffer;
735     BIO_free(mem);
736 
737     char* cipher_description =
738       SSL_CIPHER_description(SSL_get_current_cipher(ssl), NULL, 128);
739     LOG(LS_INFO) << "Cipher: " << cipher_description;
740     OPENSSL_free(cipher_description);
741   }
742 #endif
743 
744   bool ok = false;
745   int extension_count = X509_get_ext_count(certificate);
746   for (int i = 0; i < extension_count; ++i) {
747     X509_EXTENSION* extension = X509_get_ext(certificate, i);
748     int extension_nid = OBJ_obj2nid(X509_EXTENSION_get_object(extension));
749 
750     if (extension_nid == NID_subject_alt_name) {
751       const X509V3_EXT_METHOD* meth = X509V3_EXT_get(extension);
752       if (!meth)
753         break;
754 
755       void* ext_str = NULL;
756 
757       // We assign this to a local variable, instead of passing the address
758       // directly to ASN1_item_d2i.
759       // See http://readlist.com/lists/openssl.org/openssl-users/0/4761.html.
760       unsigned char* ext_value_data = extension->value->data;
761 
762       const unsigned char **ext_value_data_ptr =
763           (const_cast<const unsigned char **>(&ext_value_data));
764 
765       if (meth->it) {
766         ext_str = ASN1_item_d2i(NULL, ext_value_data_ptr,
767                                 extension->value->length,
768                                 ASN1_ITEM_ptr(meth->it));
769       } else {
770         ext_str = meth->d2i(NULL, ext_value_data_ptr, extension->value->length);
771       }
772 
773       STACK_OF(CONF_VALUE)* value = meth->i2v(meth, ext_str, NULL);
774 
775       // Cast to size_t to be compilable for both OpenSSL and BoringSSL.
776       for (size_t j = 0; j < static_cast<size_t>(sk_CONF_VALUE_num(value));
777            ++j) {
778         CONF_VALUE* nval = sk_CONF_VALUE_value(value, j);
779         // The value for nval can contain wildcards
780         if (!strcmp(nval->name, "DNS") && string_match(host, nval->value)) {
781           ok = true;
782           break;
783         }
784       }
785       sk_CONF_VALUE_pop_free(value, X509V3_conf_free);
786       value = NULL;
787 
788       if (meth->it) {
789         ASN1_item_free(reinterpret_cast<ASN1_VALUE*>(ext_str),
790                        ASN1_ITEM_ptr(meth->it));
791       } else {
792         meth->ext_free(ext_str);
793       }
794       ext_str = NULL;
795     }
796     if (ok)
797       break;
798   }
799 
800   char data[256];
801   X509_NAME* subject;
802   if (!ok
803       && ((subject = X509_get_subject_name(certificate)) != NULL)
804       && (X509_NAME_get_text_by_NID(subject, NID_commonName,
805                                     data, sizeof(data)) > 0)) {
806     data[sizeof(data)-1] = 0;
807     if (_stricmp(data, host) == 0)
808       ok = true;
809   }
810 
811   X509_free(certificate);
812 
813   // This should only ever be turned on for debugging and development.
814   if (!ok && ignore_bad_cert) {
815     LOG(LS_WARNING) << "TLS certificate check FAILED.  "
816       << "Allowing connection anyway.";
817     ok = true;
818   }
819 
820   return ok;
821 }
822 
SSLPostConnectionCheck(SSL * ssl,const char * host)823 bool OpenSSLAdapter::SSLPostConnectionCheck(SSL* ssl, const char* host) {
824   bool ok = VerifyServerName(ssl, host, ignore_bad_cert());
825 
826   if (ok) {
827     ok = (SSL_get_verify_result(ssl) == X509_V_OK ||
828           custom_verification_succeeded_);
829   }
830 
831   if (!ok && ignore_bad_cert()) {
832     LOG(LS_INFO) << "Other TLS post connection checks failed.";
833     ok = true;
834   }
835 
836   return ok;
837 }
838 
839 #if !defined(NDEBUG)
840 
841 // We only use this for tracing and so it is only needed in debug mode
842 
843 void
SSLInfoCallback(const SSL * s,int where,int ret)844 OpenSSLAdapter::SSLInfoCallback(const SSL* s, int where, int ret) {
845   const char* str = "undefined";
846   int w = where & ~SSL_ST_MASK;
847   if (w & SSL_ST_CONNECT) {
848     str = "SSL_connect";
849   } else if (w & SSL_ST_ACCEPT) {
850     str = "SSL_accept";
851   }
852   if (where & SSL_CB_LOOP) {
853     LOG(LS_INFO) <<  str << ":" << SSL_state_string_long(s);
854   } else if (where & SSL_CB_ALERT) {
855     str = (where & SSL_CB_READ) ? "read" : "write";
856     LOG(LS_INFO) <<  "SSL3 alert " << str
857       << ":" << SSL_alert_type_string_long(ret)
858       << ":" << SSL_alert_desc_string_long(ret);
859   } else if (where & SSL_CB_EXIT) {
860     if (ret == 0) {
861       LOG(LS_INFO) << str << ":failed in " << SSL_state_string_long(s);
862     } else if (ret < 0) {
863       LOG(LS_INFO) << str << ":error in " << SSL_state_string_long(s);
864     }
865   }
866 }
867 
868 #endif
869 
870 int
SSLVerifyCallback(int ok,X509_STORE_CTX * store)871 OpenSSLAdapter::SSLVerifyCallback(int ok, X509_STORE_CTX* store) {
872 #if !defined(NDEBUG)
873   if (!ok) {
874     char data[256];
875     X509* cert = X509_STORE_CTX_get_current_cert(store);
876     int depth = X509_STORE_CTX_get_error_depth(store);
877     int err = X509_STORE_CTX_get_error(store);
878 
879     LOG(LS_INFO) << "Error with certificate at depth: " << depth;
880     X509_NAME_oneline(X509_get_issuer_name(cert), data, sizeof(data));
881     LOG(LS_INFO) << "  issuer  = " << data;
882     X509_NAME_oneline(X509_get_subject_name(cert), data, sizeof(data));
883     LOG(LS_INFO) << "  subject = " << data;
884     LOG(LS_INFO) << "  err     = " << err
885       << ":" << X509_verify_cert_error_string(err);
886   }
887 #endif
888 
889   // Get our stream pointer from the store
890   SSL* ssl = reinterpret_cast<SSL*>(
891                 X509_STORE_CTX_get_ex_data(store,
892                   SSL_get_ex_data_X509_STORE_CTX_idx()));
893 
894   OpenSSLAdapter* stream =
895     reinterpret_cast<OpenSSLAdapter*>(SSL_get_app_data(ssl));
896 
897   if (!ok && custom_verify_callback_) {
898     void* cert =
899         reinterpret_cast<void*>(X509_STORE_CTX_get_current_cert(store));
900     if (custom_verify_callback_(cert)) {
901       stream->custom_verification_succeeded_ = true;
902       LOG(LS_INFO) << "validated certificate using custom callback";
903       ok = true;
904     }
905   }
906 
907   // Should only be used for debugging and development.
908   if (!ok && stream->ignore_bad_cert()) {
909     LOG(LS_WARNING) << "Ignoring cert error while verifying cert chain";
910     ok = 1;
911   }
912 
913   return ok;
914 }
915 
ConfigureTrustedRootCertificates(SSL_CTX * ctx)916 bool OpenSSLAdapter::ConfigureTrustedRootCertificates(SSL_CTX* ctx) {
917   // Add the root cert that we care about to the SSL context
918   int count_of_added_certs = 0;
919   for (size_t i = 0; i < arraysize(kSSLCertCertificateList); i++) {
920     const unsigned char* cert_buffer = kSSLCertCertificateList[i];
921     size_t cert_buffer_len = kSSLCertCertificateSizeList[i];
922     X509* cert = d2i_X509(NULL, &cert_buffer,
923                           checked_cast<long>(cert_buffer_len));
924     if (cert) {
925       int return_value = X509_STORE_add_cert(SSL_CTX_get_cert_store(ctx), cert);
926       if (return_value == 0) {
927         LOG(LS_WARNING) << "Unable to add certificate.";
928       } else {
929         count_of_added_certs++;
930       }
931       X509_free(cert);
932     }
933   }
934   return count_of_added_certs > 0;
935 }
936 
937 SSL_CTX*
SetupSSLContext()938 OpenSSLAdapter::SetupSSLContext() {
939   SSL_CTX* ctx = SSL_CTX_new(ssl_mode_ == SSL_MODE_DTLS ?
940       DTLSv1_client_method() : TLSv1_client_method());
941   if (ctx == NULL) {
942     unsigned long error = ERR_get_error();  // NOLINT: type used by OpenSSL.
943     LOG(LS_WARNING) << "SSL_CTX creation failed: "
944                     << '"' << ERR_reason_error_string(error) << "\" "
945                     << "(error=" << error << ')';
946     return NULL;
947   }
948   if (!ConfigureTrustedRootCertificates(ctx)) {
949     SSL_CTX_free(ctx);
950     return NULL;
951   }
952 
953 #if !defined(NDEBUG)
954   SSL_CTX_set_info_callback(ctx, SSLInfoCallback);
955 #endif
956 
957   SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, SSLVerifyCallback);
958   SSL_CTX_set_verify_depth(ctx, 4);
959   SSL_CTX_set_cipher_list(ctx, "ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
960 
961   if (ssl_mode_ == SSL_MODE_DTLS) {
962     SSL_CTX_set_read_ahead(ctx, 1);
963   }
964 
965   return ctx;
966 }
967 
968 } // namespace rtc
969 
970 #endif  // HAVE_OPENSSL_SSL_H
971