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