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.

939 lines
26 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. /*
  2. * libjingle
  3. * Copyright 2004--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_CONFIG_H
  28. #include "config.h"
  29. #endif // HAVE_CONFIG_H
  30. #if HAVE_OPENSSL_SSL_H
  31. #include "talk/base/opensslstreamadapter.h"
  32. #include <openssl/bio.h>
  33. #include <openssl/crypto.h>
  34. #include <openssl/err.h>
  35. #include <openssl/rand.h>
  36. #include <openssl/ssl.h>
  37. #include <openssl/x509v3.h>
  38. #include <vector>
  39. #include "talk/base/common.h"
  40. #include "talk/base/logging.h"
  41. #include "talk/base/stream.h"
  42. #include "talk/base/openssladapter.h"
  43. #include "talk/base/openssldigest.h"
  44. #include "talk/base/opensslidentity.h"
  45. #include "talk/base/stringutils.h"
  46. #include "talk/base/thread.h"
  47. namespace talk_base {
  48. #if (OPENSSL_VERSION_NUMBER >= 0x10001000L)
  49. #define HAVE_DTLS_SRTP
  50. #endif
  51. #if (OPENSSL_VERSION_NUMBER >= 0x10000000L)
  52. #define HAVE_DTLS
  53. #endif
  54. #ifdef HAVE_DTLS_SRTP
  55. // SRTP cipher suite table
  56. struct SrtpCipherMapEntry {
  57. const char* external_name;
  58. const char* internal_name;
  59. };
  60. // This isn't elegant, but it's better than an external reference
  61. static SrtpCipherMapEntry SrtpCipherMap[] = {
  62. {"AES_CM_128_HMAC_SHA1_80", "SRTP_AES128_CM_SHA1_80"},
  63. {"AES_CM_128_HMAC_SHA1_32", "SRTP_AES128_CM_SHA1_32"},
  64. {NULL, NULL}
  65. };
  66. #endif
  67. //////////////////////////////////////////////////////////////////////
  68. // StreamBIO
  69. //////////////////////////////////////////////////////////////////////
  70. static int stream_write(BIO* h, const char* buf, int num);
  71. static int stream_read(BIO* h, char* buf, int size);
  72. static int stream_puts(BIO* h, const char* str);
  73. static long stream_ctrl(BIO* h, int cmd, long arg1, void* arg2);
  74. static int stream_new(BIO* h);
  75. static int stream_free(BIO* data);
  76. static BIO_METHOD methods_stream = {
  77. BIO_TYPE_BIO,
  78. "stream",
  79. stream_write,
  80. stream_read,
  81. stream_puts,
  82. 0,
  83. stream_ctrl,
  84. stream_new,
  85. stream_free,
  86. NULL,
  87. };
  88. static BIO_METHOD* BIO_s_stream() { return(&methods_stream); }
  89. static BIO* BIO_new_stream(StreamInterface* stream) {
  90. BIO* ret = BIO_new(BIO_s_stream());
  91. if (ret == NULL)
  92. return NULL;
  93. ret->ptr = stream;
  94. return ret;
  95. }
  96. // bio methods return 1 (or at least non-zero) on success and 0 on failure.
  97. static int stream_new(BIO* b) {
  98. b->shutdown = 0;
  99. b->init = 1;
  100. b->num = 0; // 1 means end-of-stream
  101. b->ptr = 0;
  102. return 1;
  103. }
  104. static int stream_free(BIO* b) {
  105. if (b == NULL)
  106. return 0;
  107. return 1;
  108. }
  109. static int stream_read(BIO* b, char* out, int outl) {
  110. if (!out)
  111. return -1;
  112. StreamInterface* stream = static_cast<StreamInterface*>(b->ptr);
  113. BIO_clear_retry_flags(b);
  114. size_t read;
  115. int error;
  116. StreamResult result = stream->Read(out, outl, &read, &error);
  117. if (result == SR_SUCCESS) {
  118. return read;
  119. } else if (result == SR_EOS) {
  120. b->num = 1;
  121. } else if (result == SR_BLOCK) {
  122. BIO_set_retry_read(b);
  123. }
  124. return -1;
  125. }
  126. static int stream_write(BIO* b, const char* in, int inl) {
  127. if (!in)
  128. return -1;
  129. StreamInterface* stream = static_cast<StreamInterface*>(b->ptr);
  130. BIO_clear_retry_flags(b);
  131. size_t written;
  132. int error;
  133. StreamResult result = stream->Write(in, inl, &written, &error);
  134. if (result == SR_SUCCESS) {
  135. return written;
  136. } else if (result == SR_BLOCK) {
  137. BIO_set_retry_write(b);
  138. }
  139. return -1;
  140. }
  141. static int stream_puts(BIO* b, const char* str) {
  142. return stream_write(b, str, strlen(str));
  143. }
  144. static long stream_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. // OpenSSLStreamAdapter
  163. /////////////////////////////////////////////////////////////////////////////
  164. OpenSSLStreamAdapter::OpenSSLStreamAdapter(StreamInterface* stream)
  165. : SSLStreamAdapter(stream),
  166. state_(SSL_NONE),
  167. role_(SSL_CLIENT),
  168. ssl_read_needs_write_(false), ssl_write_needs_read_(false),
  169. ssl_(NULL), ssl_ctx_(NULL),
  170. custom_verification_succeeded_(false),
  171. ssl_mode_(SSL_MODE_TLS) {
  172. }
  173. OpenSSLStreamAdapter::~OpenSSLStreamAdapter() {
  174. Cleanup();
  175. }
  176. void OpenSSLStreamAdapter::SetIdentity(SSLIdentity* identity) {
  177. ASSERT(!identity_);
  178. identity_.reset(static_cast<OpenSSLIdentity*>(identity));
  179. }
  180. void OpenSSLStreamAdapter::SetServerRole(SSLRole role) {
  181. role_ = role;
  182. }
  183. void OpenSSLStreamAdapter::SetPeerCertificate(SSLCertificate* cert) {
  184. ASSERT(!peer_certificate_);
  185. ASSERT(peer_certificate_digest_algorithm_.empty());
  186. ASSERT(ssl_server_name_.empty());
  187. peer_certificate_.reset(static_cast<OpenSSLCertificate*>(cert));
  188. }
  189. bool OpenSSLStreamAdapter::SetPeerCertificateDigest(const std::string
  190. &digest_alg,
  191. const unsigned char*
  192. digest_val,
  193. size_t digest_len) {
  194. ASSERT(!peer_certificate_);
  195. ASSERT(peer_certificate_digest_algorithm_.size() == 0);
  196. ASSERT(ssl_server_name_.empty());
  197. size_t expected_len;
  198. if (!OpenSSLDigest::GetDigestSize(digest_alg, &expected_len)) {
  199. LOG(LS_WARNING) << "Unknown digest algorithm: " << digest_alg;
  200. return false;
  201. }
  202. if (expected_len != digest_len)
  203. return false;
  204. peer_certificate_digest_value_.SetData(digest_val, digest_len);
  205. peer_certificate_digest_algorithm_ = digest_alg;
  206. return true;
  207. }
  208. // Key Extractor interface
  209. bool OpenSSLStreamAdapter::ExportKeyingMaterial(const std::string& label,
  210. const uint8* context,
  211. size_t context_len,
  212. bool use_context,
  213. uint8* result,
  214. size_t result_len) {
  215. #ifdef HAVE_DTLS_SRTP
  216. int i;
  217. i = SSL_export_keying_material(ssl_, result, result_len,
  218. label.c_str(), label.length(),
  219. const_cast<uint8 *>(context),
  220. context_len, use_context);
  221. if (i != 1)
  222. return false;
  223. return true;
  224. #else
  225. return false;
  226. #endif
  227. }
  228. bool OpenSSLStreamAdapter::SetDtlsSrtpCiphers(
  229. const std::vector<std::string>& ciphers) {
  230. std::string internal_ciphers;
  231. if (state_ != SSL_NONE)
  232. return false;
  233. #ifdef HAVE_DTLS_SRTP
  234. for (std::vector<std::string>::const_iterator cipher = ciphers.begin();
  235. cipher != ciphers.end(); ++cipher) {
  236. bool found = false;
  237. for (SrtpCipherMapEntry *entry = SrtpCipherMap; entry->internal_name;
  238. ++entry) {
  239. if (*cipher == entry->external_name) {
  240. found = true;
  241. if (!internal_ciphers.empty())
  242. internal_ciphers += ":";
  243. internal_ciphers += entry->internal_name;
  244. break;
  245. }
  246. }
  247. if (!found) {
  248. LOG(LS_ERROR) << "Could not find cipher: " << *cipher;
  249. return false;
  250. }
  251. }
  252. if (internal_ciphers.empty())
  253. return false;
  254. srtp_ciphers_ = internal_ciphers;
  255. return true;
  256. #else
  257. return false;
  258. #endif
  259. }
  260. bool OpenSSLStreamAdapter::GetDtlsSrtpCipher(std::string* cipher) {
  261. #ifdef HAVE_DTLS_SRTP
  262. ASSERT(state_ == SSL_CONNECTED);
  263. if (state_ != SSL_CONNECTED)
  264. return false;
  265. SRTP_PROTECTION_PROFILE *srtp_profile =
  266. SSL_get_selected_srtp_profile(ssl_);
  267. if (!srtp_profile)
  268. return false;
  269. for (SrtpCipherMapEntry *entry = SrtpCipherMap;
  270. entry->internal_name; ++entry) {
  271. if (!strcmp(entry->internal_name, srtp_profile->name)) {
  272. *cipher = entry->external_name;
  273. return true;
  274. }
  275. }
  276. ASSERT(false); // This should never happen
  277. return false;
  278. #else
  279. return false;
  280. #endif
  281. }
  282. int OpenSSLStreamAdapter::StartSSLWithServer(const char* server_name) {
  283. ASSERT(server_name != NULL && server_name[0] != '\0');
  284. ssl_server_name_ = server_name;
  285. return StartSSL();
  286. }
  287. int OpenSSLStreamAdapter::StartSSLWithPeer() {
  288. ASSERT(ssl_server_name_.empty());
  289. // It is permitted to specify peer_certificate_ only later.
  290. return StartSSL();
  291. }
  292. void OpenSSLStreamAdapter::SetMode(SSLMode mode) {
  293. ASSERT(state_ == SSL_NONE);
  294. ssl_mode_ = mode;
  295. }
  296. //
  297. // StreamInterface Implementation
  298. //
  299. StreamResult OpenSSLStreamAdapter::Write(const void* data, size_t data_len,
  300. size_t* written, int* error) {
  301. LOG(LS_INFO) << "OpenSSLStreamAdapter::Write(" << data_len << ")";
  302. switch (state_) {
  303. case SSL_NONE:
  304. // pass-through in clear text
  305. return StreamAdapterInterface::Write(data, data_len, written, error);
  306. case SSL_WAIT:
  307. case SSL_CONNECTING:
  308. return SR_BLOCK;
  309. case SSL_CONNECTED:
  310. break;
  311. case SSL_ERROR:
  312. case SSL_CLOSED:
  313. default:
  314. if (error)
  315. *error = ssl_error_code_;
  316. return SR_ERROR;
  317. }
  318. // OpenSSL will return an error if we try to write zero bytes
  319. if (data_len == 0) {
  320. if (written)
  321. *written = 0;
  322. return SR_SUCCESS;
  323. }
  324. ssl_write_needs_read_ = false;
  325. int code = SSL_write(ssl_, data, data_len);
  326. int ssl_error = SSL_get_error(ssl_, code);
  327. switch (ssl_error) {
  328. case SSL_ERROR_NONE:
  329. LOG(LS_INFO) << " -- success";
  330. ASSERT(0 < code && static_cast<unsigned>(code) <= data_len);
  331. if (written)
  332. *written = code;
  333. return SR_SUCCESS;
  334. case SSL_ERROR_WANT_READ:
  335. LOG(LS_INFO) << " -- error want read";
  336. ssl_write_needs_read_ = true;
  337. return SR_BLOCK;
  338. case SSL_ERROR_WANT_WRITE:
  339. LOG(LS_INFO) << " -- error want write";
  340. return SR_BLOCK;
  341. case SSL_ERROR_ZERO_RETURN:
  342. default:
  343. Error("SSL_write", (ssl_error ? ssl_error : -1), false);
  344. if (error)
  345. *error = ssl_error_code_;
  346. return SR_ERROR;
  347. }
  348. // not reached
  349. }
  350. StreamResult OpenSSLStreamAdapter::Read(void* data, size_t data_len,
  351. size_t* read, int* error) {
  352. LOG(LS_INFO) << "OpenSSLStreamAdapter::Read(" << data_len << ")";
  353. switch (state_) {
  354. case SSL_NONE:
  355. // pass-through in clear text
  356. return StreamAdapterInterface::Read(data, data_len, read, error);
  357. case SSL_WAIT:
  358. case SSL_CONNECTING:
  359. return SR_BLOCK;
  360. case SSL_CONNECTED:
  361. break;
  362. case SSL_CLOSED:
  363. return SR_EOS;
  364. case SSL_ERROR:
  365. default:
  366. if (error)
  367. *error = ssl_error_code_;
  368. return SR_ERROR;
  369. }
  370. // Don't trust OpenSSL with zero byte reads
  371. if (data_len == 0) {
  372. if (read)
  373. *read = 0;
  374. return SR_SUCCESS;
  375. }
  376. ssl_read_needs_write_ = false;
  377. int code = SSL_read(ssl_, data, data_len);
  378. int ssl_error = SSL_get_error(ssl_, code);
  379. switch (ssl_error) {
  380. case SSL_ERROR_NONE:
  381. LOG(LS_INFO) << " -- success";
  382. ASSERT(0 < code && static_cast<unsigned>(code) <= data_len);
  383. if (read)
  384. *read = code;
  385. if (ssl_mode_ == SSL_MODE_DTLS) {
  386. // Enforce atomic reads -- this is a short read
  387. unsigned int pending = SSL_pending(ssl_);
  388. if (pending) {
  389. LOG(LS_INFO) << " -- short DTLS read. flushing";
  390. FlushInput(pending);
  391. if (error)
  392. *error = SSE_MSG_TRUNC;
  393. return SR_ERROR;
  394. }
  395. }
  396. return SR_SUCCESS;
  397. case SSL_ERROR_WANT_READ:
  398. LOG(LS_INFO) << " -- error want read";
  399. return SR_BLOCK;
  400. case SSL_ERROR_WANT_WRITE:
  401. LOG(LS_INFO) << " -- error want write";
  402. ssl_read_needs_write_ = true;
  403. return SR_BLOCK;
  404. case SSL_ERROR_ZERO_RETURN:
  405. LOG(LS_INFO) << " -- remote side closed";
  406. return SR_EOS;
  407. break;
  408. default:
  409. LOG(LS_INFO) << " -- error " << code;
  410. Error("SSL_read", (ssl_error ? ssl_error : -1), false);
  411. if (error)
  412. *error = ssl_error_code_;
  413. return SR_ERROR;
  414. }
  415. // not reached
  416. }
  417. void OpenSSLStreamAdapter::FlushInput(unsigned int left) {
  418. unsigned char buf[2048];
  419. while (left) {
  420. // This should always succeed
  421. int toread = (sizeof(buf) < left) ? sizeof(buf) : left;
  422. int code = SSL_read(ssl_, buf, toread);
  423. int ssl_error = SSL_get_error(ssl_, code);
  424. ASSERT(ssl_error == SSL_ERROR_NONE);
  425. if (ssl_error != SSL_ERROR_NONE) {
  426. LOG(LS_INFO) << " -- error " << code;
  427. Error("SSL_read", (ssl_error ? ssl_error : -1), false);
  428. return;
  429. }
  430. LOG(LS_INFO) << " -- flushed " << code << " bytes";
  431. left -= code;
  432. }
  433. }
  434. void OpenSSLStreamAdapter::Close() {
  435. Cleanup();
  436. ASSERT(state_ == SSL_CLOSED || state_ == SSL_ERROR);
  437. StreamAdapterInterface::Close();
  438. }
  439. StreamState OpenSSLStreamAdapter::GetState() const {
  440. switch (state_) {
  441. case SSL_WAIT:
  442. case SSL_CONNECTING:
  443. return SS_OPENING;
  444. case SSL_CONNECTED:
  445. return SS_OPEN;
  446. default:
  447. return SS_CLOSED;
  448. };
  449. // not reached
  450. }
  451. void OpenSSLStreamAdapter::OnEvent(StreamInterface* stream, int events,
  452. int err) {
  453. int events_to_signal = 0;
  454. int signal_error = 0;
  455. ASSERT(stream == this->stream());
  456. if ((events & SE_OPEN)) {
  457. LOG(LS_INFO) << "OpenSSLStreamAdapter::OnEvent SE_OPEN";
  458. if (state_ != SSL_WAIT) {
  459. ASSERT(state_ == SSL_NONE);
  460. events_to_signal |= SE_OPEN;
  461. } else {
  462. state_ = SSL_CONNECTING;
  463. if (int err = BeginSSL()) {
  464. Error("BeginSSL", err, true);
  465. return;
  466. }
  467. }
  468. }
  469. if ((events & (SE_READ|SE_WRITE))) {
  470. LOG(LS_INFO) << "OpenSSLStreamAdapter::OnEvent"
  471. << ((events & SE_READ) ? " SE_READ" : "")
  472. << ((events & SE_WRITE) ? " SE_WRITE" : "");
  473. if (state_ == SSL_NONE) {
  474. events_to_signal |= events & (SE_READ|SE_WRITE);
  475. } else if (state_ == SSL_CONNECTING) {
  476. if (int err = ContinueSSL()) {
  477. Error("ContinueSSL", err, true);
  478. return;
  479. }
  480. } else if (state_ == SSL_CONNECTED) {
  481. if (((events & SE_READ) && ssl_write_needs_read_) ||
  482. (events & SE_WRITE)) {
  483. LOG(LS_INFO) << " -- onStreamWriteable";
  484. events_to_signal |= SE_WRITE;
  485. }
  486. if (((events & SE_WRITE) && ssl_read_needs_write_) ||
  487. (events & SE_READ)) {
  488. LOG(LS_INFO) << " -- onStreamReadable";
  489. events_to_signal |= SE_READ;
  490. }
  491. }
  492. }
  493. if ((events & SE_CLOSE)) {
  494. LOG(LS_INFO) << "OpenSSLStreamAdapter::OnEvent(SE_CLOSE, " << err << ")";
  495. Cleanup();
  496. events_to_signal |= SE_CLOSE;
  497. // SE_CLOSE is the only event that uses the final parameter to OnEvent().
  498. ASSERT(signal_error == 0);
  499. signal_error = err;
  500. }
  501. if (events_to_signal)
  502. StreamAdapterInterface::OnEvent(stream, events_to_signal, signal_error);
  503. }
  504. int OpenSSLStreamAdapter::StartSSL() {
  505. ASSERT(state_ == SSL_NONE);
  506. if (StreamAdapterInterface::GetState() != SS_OPEN) {
  507. state_ = SSL_WAIT;
  508. return 0;
  509. }
  510. state_ = SSL_CONNECTING;
  511. if (int err = BeginSSL()) {
  512. Error("BeginSSL", err, false);
  513. return err;
  514. }
  515. return 0;
  516. }
  517. int OpenSSLStreamAdapter::BeginSSL() {
  518. ASSERT(state_ == SSL_CONNECTING);
  519. // The underlying stream has open. If we are in peer-to-peer mode
  520. // then a peer certificate must have been specified by now.
  521. ASSERT(!ssl_server_name_.empty() ||
  522. peer_certificate_ ||
  523. !peer_certificate_digest_algorithm_.empty());
  524. LOG(LS_INFO) << "BeginSSL: "
  525. << (!ssl_server_name_.empty() ? ssl_server_name_ :
  526. "with peer");
  527. BIO* bio = NULL;
  528. // First set up the context
  529. ASSERT(ssl_ctx_ == NULL);
  530. ssl_ctx_ = SetupSSLContext();
  531. if (!ssl_ctx_)
  532. return -1;
  533. bio = BIO_new_stream(static_cast<StreamInterface*>(stream()));
  534. if (!bio)
  535. return -1;
  536. ssl_ = SSL_new(ssl_ctx_);
  537. if (!ssl_) {
  538. BIO_free(bio);
  539. return -1;
  540. }
  541. SSL_set_app_data(ssl_, this);
  542. SSL_set_bio(ssl_, bio, bio); // the SSL object owns the bio now.
  543. SSL_set_mode(ssl_, SSL_MODE_ENABLE_PARTIAL_WRITE |
  544. SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
  545. // Do the connect
  546. return ContinueSSL();
  547. }
  548. int OpenSSLStreamAdapter::ContinueSSL() {
  549. LOG(LS_INFO) << "ContinueSSL";
  550. ASSERT(state_ == SSL_CONNECTING);
  551. // Clear the DTLS timer
  552. Thread::Current()->Clear(this, MSG_TIMEOUT);
  553. int code = (role_ == SSL_CLIENT) ? SSL_connect(ssl_) : SSL_accept(ssl_);
  554. int ssl_error;
  555. switch (ssl_error = SSL_get_error(ssl_, code)) {
  556. case SSL_ERROR_NONE:
  557. LOG(LS_INFO) << " -- success";
  558. if (!SSLPostConnectionCheck(ssl_, ssl_server_name_.c_str(),
  559. peer_certificate_ ?
  560. peer_certificate_->x509() : NULL,
  561. peer_certificate_digest_algorithm_)) {
  562. LOG(LS_ERROR) << "TLS post connection check failed";
  563. return -1;
  564. }
  565. state_ = SSL_CONNECTED;
  566. StreamAdapterInterface::OnEvent(stream(), SE_OPEN|SE_READ|SE_WRITE, 0);
  567. break;
  568. case SSL_ERROR_WANT_READ: {
  569. LOG(LS_INFO) << " -- error want read";
  570. #ifdef HAVE_DTLS
  571. struct timeval timeout;
  572. if (DTLSv1_get_timeout(ssl_, &timeout)) {
  573. int delay = timeout.tv_sec * 1000 + timeout.tv_usec/1000;
  574. Thread::Current()->PostDelayed(delay, this, MSG_TIMEOUT, 0);
  575. }
  576. #endif
  577. }
  578. break;
  579. case SSL_ERROR_WANT_WRITE:
  580. LOG(LS_INFO) << " -- error want write";
  581. break;
  582. case SSL_ERROR_ZERO_RETURN:
  583. default:
  584. LOG(LS_INFO) << " -- error " << code;
  585. return (ssl_error != 0) ? ssl_error : -1;
  586. }
  587. return 0;
  588. }
  589. void OpenSSLStreamAdapter::Error(const char* context, int err, bool signal) {
  590. LOG(LS_WARNING) << "OpenSSLStreamAdapter::Error("
  591. << context << ", " << err << ")";
  592. state_ = SSL_ERROR;
  593. ssl_error_code_ = err;
  594. Cleanup();
  595. if (signal)
  596. StreamAdapterInterface::OnEvent(stream(), SE_CLOSE, err);
  597. }
  598. void OpenSSLStreamAdapter::Cleanup() {
  599. LOG(LS_INFO) << "Cleanup";
  600. if (state_ != SSL_ERROR) {
  601. state_ = SSL_CLOSED;
  602. ssl_error_code_ = 0;
  603. }
  604. if (ssl_) {
  605. SSL_free(ssl_);
  606. ssl_ = NULL;
  607. }
  608. if (ssl_ctx_) {
  609. SSL_CTX_free(ssl_ctx_);
  610. ssl_ctx_ = NULL;
  611. }
  612. identity_.reset();
  613. peer_certificate_.reset();
  614. // Clear the DTLS timer
  615. Thread::Current()->Clear(this, MSG_TIMEOUT);
  616. }
  617. void OpenSSLStreamAdapter::OnMessage(Message* msg) {
  618. // Process our own messages and then pass others to the superclass
  619. if (MSG_TIMEOUT == msg->message_id) {
  620. LOG(LS_INFO) << "DTLS timeout expired";
  621. #ifdef HAVE_DTLS
  622. DTLSv1_handle_timeout(ssl_);
  623. #endif
  624. ContinueSSL();
  625. } else {
  626. StreamInterface::OnMessage(msg);
  627. }
  628. }
  629. SSL_CTX* OpenSSLStreamAdapter::SetupSSLContext() {
  630. SSL_CTX *ctx = NULL;
  631. if (role_ == SSL_CLIENT) {
  632. #ifdef HAVE_DTLS
  633. ctx = SSL_CTX_new(ssl_mode_ == SSL_MODE_DTLS ?
  634. DTLSv1_client_method() : TLSv1_client_method());
  635. #else
  636. ctx = SSL_CTX_new(TLSv1_client_method());
  637. #endif
  638. } else {
  639. #ifdef HAVE_DTLS
  640. ctx = SSL_CTX_new(ssl_mode_ == SSL_MODE_DTLS ?
  641. DTLSv1_server_method() : TLSv1_server_method());
  642. #else
  643. ctx = SSL_CTX_new(TLSv1_server_method());
  644. #endif
  645. }
  646. if (ctx == NULL)
  647. return NULL;
  648. if (identity_ && !identity_->ConfigureIdentity(ctx)) {
  649. SSL_CTX_free(ctx);
  650. return NULL;
  651. }
  652. if (!peer_certificate_) { // traditional mode
  653. // Add the root cert to the SSL context
  654. if (!OpenSSLAdapter::ConfigureTrustedRootCertificates(ctx)) {
  655. SSL_CTX_free(ctx);
  656. return NULL;
  657. }
  658. }
  659. if (peer_certificate_ && role_ == SSL_SERVER)
  660. // we must specify which client cert to ask for
  661. SSL_CTX_add_client_CA(ctx, peer_certificate_->x509());
  662. #ifdef _DEBUG
  663. SSL_CTX_set_info_callback(ctx, OpenSSLAdapter::SSLInfoCallback);
  664. #endif
  665. SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER |SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  666. SSLVerifyCallback);
  667. SSL_CTX_set_verify_depth(ctx, 4);
  668. SSL_CTX_set_cipher_list(ctx, "ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
  669. #ifdef HAVE_DTLS_SRTP
  670. if (!srtp_ciphers_.empty()) {
  671. if (SSL_CTX_set_tlsext_use_srtp(ctx, srtp_ciphers_.c_str())) {
  672. SSL_CTX_free(ctx);
  673. return NULL;
  674. }
  675. }
  676. #endif
  677. return ctx;
  678. }
  679. int OpenSSLStreamAdapter::SSLVerifyCallback(int ok, X509_STORE_CTX* store) {
  680. #if _DEBUG
  681. if (!ok) {
  682. char data[256];
  683. X509* cert = X509_STORE_CTX_get_current_cert(store);
  684. int depth = X509_STORE_CTX_get_error_depth(store);
  685. int err = X509_STORE_CTX_get_error(store);
  686. LOG(LS_INFO) << "Error with certificate at depth: " << depth;
  687. X509_NAME_oneline(X509_get_issuer_name(cert), data, sizeof(data));
  688. LOG(LS_INFO) << " issuer = " << data;
  689. X509_NAME_oneline(X509_get_subject_name(cert), data, sizeof(data));
  690. LOG(LS_INFO) << " subject = " << data;
  691. LOG(LS_INFO) << " err = " << err
  692. << ":" << X509_verify_cert_error_string(err);
  693. }
  694. #endif
  695. // Get our SSL structure from the store
  696. SSL* ssl = reinterpret_cast<SSL*>(X509_STORE_CTX_get_ex_data(
  697. store,
  698. SSL_get_ex_data_X509_STORE_CTX_idx()));
  699. OpenSSLStreamAdapter* stream =
  700. reinterpret_cast<OpenSSLStreamAdapter*>(SSL_get_app_data(ssl));
  701. // In peer-to-peer mode, no root cert / certificate authority was
  702. // specified, so the libraries knows of no certificate to accept,
  703. // and therefore it will necessarily call here on the first cert it
  704. // tries to verify.
  705. if (!ok && stream->peer_certificate_) {
  706. X509* cert = X509_STORE_CTX_get_current_cert(store);
  707. int err = X509_STORE_CTX_get_error(store);
  708. // peer-to-peer mode: allow the certificate to be self-signed,
  709. // assuming it matches the cert that was specified.
  710. if (err == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT &&
  711. X509_cmp(cert, stream->peer_certificate_->x509()) == 0) {
  712. LOG(LS_INFO) << "Accepted self-signed peer certificate authority";
  713. ok = 1;
  714. }
  715. } else if (!ok && !stream->peer_certificate_digest_algorithm_.empty()) {
  716. X509* cert = X509_STORE_CTX_get_current_cert(store);
  717. int err = X509_STORE_CTX_get_error(store);
  718. // peer-to-peer mode: allow the certificate to be self-signed,
  719. // assuming it matches the digest that was specified.
  720. if (err == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT) {
  721. unsigned char digest[EVP_MAX_MD_SIZE];
  722. std::size_t digest_length;
  723. if (OpenSSLCertificate::
  724. ComputeDigest(cert,
  725. stream->peer_certificate_digest_algorithm_,
  726. digest, sizeof(digest),
  727. &digest_length)) {
  728. Buffer computed_digest(digest, digest_length);
  729. if (computed_digest == stream->peer_certificate_digest_value_) {
  730. LOG(LS_INFO) <<
  731. "Accepted self-signed peer certificate authority";
  732. ok = 1;
  733. }
  734. }
  735. }
  736. } else if (!ok && OpenSSLAdapter::custom_verify_callback_) {
  737. // this applies only in traditional mode
  738. void* cert =
  739. reinterpret_cast<void*>(X509_STORE_CTX_get_current_cert(store));
  740. if (OpenSSLAdapter::custom_verify_callback_(cert)) {
  741. stream->custom_verification_succeeded_ = true;
  742. LOG(LS_INFO) << "validated certificate using custom callback";
  743. ok = 1;
  744. }
  745. }
  746. if (!ok && stream->ignore_bad_cert()) {
  747. LOG(LS_WARNING) << "Ignoring cert error while verifying cert chain";
  748. ok = 1;
  749. }
  750. return ok;
  751. }
  752. // This code is taken from the "Network Security with OpenSSL"
  753. // sample in chapter 5
  754. bool OpenSSLStreamAdapter::SSLPostConnectionCheck(SSL* ssl,
  755. const char* server_name,
  756. const X509* peer_cert,
  757. const std::string
  758. &peer_digest) {
  759. ASSERT(server_name != NULL);
  760. bool ok;
  761. if (server_name[0] != '\0') { // traditional mode
  762. ok = OpenSSLAdapter::VerifyServerName(ssl, server_name, ignore_bad_cert());
  763. if (ok) {
  764. ok = (SSL_get_verify_result(ssl) == X509_V_OK ||
  765. custom_verification_succeeded_);
  766. }
  767. } else { // peer-to-peer mode
  768. ASSERT((peer_cert != NULL) || (!peer_digest.empty()));
  769. // no server name validation
  770. ok = true;
  771. }
  772. if (!ok && ignore_bad_cert()) {
  773. LOG(LS_ERROR) << "SSL_get_verify_result(ssl) = "
  774. << SSL_get_verify_result(ssl);
  775. LOG(LS_INFO) << "Other TLS post connection checks failed.";
  776. ok = true;
  777. }
  778. return ok;
  779. }
  780. bool OpenSSLStreamAdapter::HaveDtls() {
  781. #ifdef HAVE_DTLS
  782. return true;
  783. #else
  784. return false;
  785. #endif
  786. }
  787. bool OpenSSLStreamAdapter::HaveDtlsSrtp() {
  788. #ifdef HAVE_DTLS_SRTP
  789. return true;
  790. #else
  791. return false;
  792. #endif
  793. }
  794. bool OpenSSLStreamAdapter::HaveExporter() {
  795. #ifdef HAVE_DTLS_SRTP
  796. return true;
  797. #else
  798. return false;
  799. #endif
  800. }
  801. } // namespace talk_base
  802. #endif // HAVE_OPENSSL_SSL_H