You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

903 lines
23 KiB

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