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.

1007 lines
26 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. /*
  2. * libjingle
  3. * Copyright 2004--2008, Google Inc.
  4. * Copyright 2004--2011, RTFM, Inc.
  5. *
  6. * Redistribution and use in source and binary forms, with or without
  7. * modification, are permitted provided that the following conditions are met:
  8. *
  9. * 1. Redistributions of source code must retain the above copyright notice,
  10. * this list of conditions and the following disclaimer.
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. * 3. The name of the author may not be used to endorse or promote products
  15. * derived from this software without specific prior written permission.
  16. *
  17. * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
  18. * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
  19. * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
  20. * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  21. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  22. * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
  23. * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
  24. * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
  25. * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  26. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  27. */
  28. #include <vector>
  29. #if HAVE_CONFIG_H
  30. #include "config.h"
  31. #endif // HAVE_CONFIG_H
  32. #if HAVE_NSS_SSL_H
  33. #include "talk/base/nssstreamadapter.h"
  34. #include "keyhi.h"
  35. #include "nspr.h"
  36. #include "nss.h"
  37. #include "pk11pub.h"
  38. #include "secerr.h"
  39. #ifdef NSS_SSL_RELATIVE_PATH
  40. #include "ssl.h"
  41. #include "sslerr.h"
  42. #include "sslproto.h"
  43. #else
  44. #include "net/third_party/nss/ssl/ssl.h"
  45. #include "net/third_party/nss/ssl/sslerr.h"
  46. #include "net/third_party/nss/ssl/sslproto.h"
  47. #endif
  48. #include "talk/base/nssidentity.h"
  49. #include "talk/base/thread.h"
  50. namespace talk_base {
  51. PRDescIdentity NSSStreamAdapter::nspr_layer_identity = PR_INVALID_IO_LAYER;
  52. #define UNIMPLEMENTED \
  53. PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0); \
  54. LOG(LS_ERROR) \
  55. << "Call to unimplemented function "<< __FUNCTION__; ASSERT(false)
  56. #ifdef SRTP_AES128_CM_HMAC_SHA1_80
  57. #define HAVE_DTLS_SRTP
  58. #endif
  59. #ifdef HAVE_DTLS_SRTP
  60. // SRTP cipher suite table
  61. struct SrtpCipherMapEntry {
  62. const char* external_name;
  63. PRUint16 cipher_id;
  64. };
  65. // This isn't elegant, but it's better than an external reference
  66. static const SrtpCipherMapEntry kSrtpCipherMap[] = {
  67. {"AES_CM_128_HMAC_SHA1_80", SRTP_AES128_CM_HMAC_SHA1_80 },
  68. {"AES_CM_128_HMAC_SHA1_32", SRTP_AES128_CM_HMAC_SHA1_32 },
  69. {NULL, 0}
  70. };
  71. #endif
  72. // Implementation of NSPR methods
  73. static PRStatus StreamClose(PRFileDesc *socket) {
  74. // Noop
  75. return PR_SUCCESS;
  76. }
  77. static PRInt32 StreamRead(PRFileDesc *socket, void *buf, PRInt32 length) {
  78. StreamInterface *stream = reinterpret_cast<StreamInterface *>(socket->secret);
  79. size_t read;
  80. int error;
  81. StreamResult result = stream->Read(buf, length, &read, &error);
  82. if (result == SR_SUCCESS) {
  83. return read;
  84. }
  85. if (result == SR_EOS) {
  86. return 0;
  87. }
  88. if (result == SR_BLOCK) {
  89. PR_SetError(PR_WOULD_BLOCK_ERROR, 0);
  90. return -1;
  91. }
  92. PR_SetError(PR_UNKNOWN_ERROR, error);
  93. return -1;
  94. }
  95. static PRInt32 StreamWrite(PRFileDesc *socket, const void *buf,
  96. PRInt32 length) {
  97. StreamInterface *stream = reinterpret_cast<StreamInterface *>(socket->secret);
  98. size_t written;
  99. int error;
  100. StreamResult result = stream->Write(buf, length, &written, &error);
  101. if (result == SR_SUCCESS) {
  102. return written;
  103. }
  104. if (result == SR_BLOCK) {
  105. LOG(LS_INFO) <<
  106. "NSSStreamAdapter: write to underlying transport would block";
  107. PR_SetError(PR_WOULD_BLOCK_ERROR, 0);
  108. return -1;
  109. }
  110. LOG(LS_ERROR) << "Write error";
  111. PR_SetError(PR_UNKNOWN_ERROR, error);
  112. return -1;
  113. }
  114. static PRInt32 StreamAvailable(PRFileDesc *socket) {
  115. UNIMPLEMENTED;
  116. return -1;
  117. }
  118. PRInt64 StreamAvailable64(PRFileDesc *socket) {
  119. UNIMPLEMENTED;
  120. return -1;
  121. }
  122. static PRStatus StreamSync(PRFileDesc *socket) {
  123. UNIMPLEMENTED;
  124. return PR_FAILURE;
  125. }
  126. static PROffset32 StreamSeek(PRFileDesc *socket, PROffset32 offset,
  127. PRSeekWhence how) {
  128. UNIMPLEMENTED;
  129. return -1;
  130. }
  131. static PROffset64 StreamSeek64(PRFileDesc *socket, PROffset64 offset,
  132. PRSeekWhence how) {
  133. UNIMPLEMENTED;
  134. return -1;
  135. }
  136. static PRStatus StreamFileInfo(PRFileDesc *socket, PRFileInfo *info) {
  137. UNIMPLEMENTED;
  138. return PR_FAILURE;
  139. }
  140. static PRStatus StreamFileInfo64(PRFileDesc *socket, PRFileInfo64 *info) {
  141. UNIMPLEMENTED;
  142. return PR_FAILURE;
  143. }
  144. static PRInt32 StreamWritev(PRFileDesc *socket, const PRIOVec *iov,
  145. PRInt32 iov_size, PRIntervalTime timeout) {
  146. UNIMPLEMENTED;
  147. return -1;
  148. }
  149. static PRStatus StreamConnect(PRFileDesc *socket, const PRNetAddr *addr,
  150. PRIntervalTime timeout) {
  151. UNIMPLEMENTED;
  152. return PR_FAILURE;
  153. }
  154. static PRFileDesc *StreamAccept(PRFileDesc *sd, PRNetAddr *addr,
  155. PRIntervalTime timeout) {
  156. UNIMPLEMENTED;
  157. return NULL;
  158. }
  159. static PRStatus StreamBind(PRFileDesc *socket, const PRNetAddr *addr) {
  160. UNIMPLEMENTED;
  161. return PR_FAILURE;
  162. }
  163. static PRStatus StreamListen(PRFileDesc *socket, PRIntn depth) {
  164. UNIMPLEMENTED;
  165. return PR_FAILURE;
  166. }
  167. static PRStatus StreamShutdown(PRFileDesc *socket, PRIntn how) {
  168. UNIMPLEMENTED;
  169. return PR_FAILURE;
  170. }
  171. // Note: this is always nonblocking and ignores the timeout.
  172. // TODO(ekr@rtfm.com): In future verify that the socket is
  173. // actually in non-blocking mode.
  174. // This function does not support peek.
  175. static PRInt32 StreamRecv(PRFileDesc *socket, void *buf, PRInt32 amount,
  176. PRIntn flags, PRIntervalTime to) {
  177. ASSERT(flags == 0);
  178. if (flags != 0) {
  179. PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
  180. return -1;
  181. }
  182. return StreamRead(socket, buf, amount);
  183. }
  184. // Note: this is always nonblocking and assumes a zero timeout.
  185. // This function does not support peek.
  186. static PRInt32 StreamSend(PRFileDesc *socket, const void *buf,
  187. PRInt32 amount, PRIntn flags,
  188. PRIntervalTime to) {
  189. ASSERT(flags == 0);
  190. return StreamWrite(socket, buf, amount);
  191. }
  192. static PRInt32 StreamRecvfrom(PRFileDesc *socket, void *buf,
  193. PRInt32 amount, PRIntn flags,
  194. PRNetAddr *addr, PRIntervalTime to) {
  195. UNIMPLEMENTED;
  196. return -1;
  197. }
  198. static PRInt32 StreamSendto(PRFileDesc *socket, const void *buf,
  199. PRInt32 amount, PRIntn flags,
  200. const PRNetAddr *addr, PRIntervalTime to) {
  201. UNIMPLEMENTED;
  202. return -1;
  203. }
  204. static PRInt16 StreamPoll(PRFileDesc *socket, PRInt16 in_flags,
  205. PRInt16 *out_flags) {
  206. UNIMPLEMENTED;
  207. return -1;
  208. }
  209. static PRInt32 StreamAcceptRead(PRFileDesc *sd, PRFileDesc **nd,
  210. PRNetAddr **raddr,
  211. void *buf, PRInt32 amount, PRIntervalTime t) {
  212. UNIMPLEMENTED;
  213. return -1;
  214. }
  215. static PRInt32 StreamTransmitFile(PRFileDesc *sd, PRFileDesc *socket,
  216. const void *headers, PRInt32 hlen,
  217. PRTransmitFileFlags flags, PRIntervalTime t) {
  218. UNIMPLEMENTED;
  219. return -1;
  220. }
  221. static PRStatus StreamGetPeerName(PRFileDesc *socket, PRNetAddr *addr) {
  222. // TODO(ekr@rtfm.com): Modify to return unique names for each channel
  223. // somehow, as opposed to always the same static address. The current
  224. // implementation messes up the session cache, which is why it's off
  225. // elsewhere
  226. addr->inet.family = PR_AF_INET;
  227. addr->inet.port = 0;
  228. addr->inet.ip = 0;
  229. return PR_SUCCESS;
  230. }
  231. static PRStatus StreamGetSockName(PRFileDesc *socket, PRNetAddr *addr) {
  232. UNIMPLEMENTED;
  233. return PR_FAILURE;
  234. }
  235. static PRStatus StreamGetSockOption(PRFileDesc *socket, PRSocketOptionData *opt) {
  236. switch (opt->option) {
  237. case PR_SockOpt_Nonblocking:
  238. opt->value.non_blocking = PR_TRUE;
  239. return PR_SUCCESS;
  240. default:
  241. UNIMPLEMENTED;
  242. break;
  243. }
  244. return PR_FAILURE;
  245. }
  246. // Imitate setting socket options. These are mostly noops.
  247. static PRStatus StreamSetSockOption(PRFileDesc *socket,
  248. const PRSocketOptionData *opt) {
  249. switch (opt->option) {
  250. case PR_SockOpt_Nonblocking:
  251. return PR_SUCCESS;
  252. case PR_SockOpt_NoDelay:
  253. return PR_SUCCESS;
  254. default:
  255. UNIMPLEMENTED;
  256. break;
  257. }
  258. return PR_FAILURE;
  259. }
  260. static PRInt32 StreamSendfile(PRFileDesc *out, PRSendFileData *in,
  261. PRTransmitFileFlags flags, PRIntervalTime to) {
  262. UNIMPLEMENTED;
  263. return -1;
  264. }
  265. static PRStatus StreamConnectContinue(PRFileDesc *socket, PRInt16 flags) {
  266. UNIMPLEMENTED;
  267. return PR_FAILURE;
  268. }
  269. static PRIntn StreamReserved(PRFileDesc *socket) {
  270. UNIMPLEMENTED;
  271. return -1;
  272. }
  273. static const struct PRIOMethods nss_methods = {
  274. PR_DESC_LAYERED,
  275. StreamClose,
  276. StreamRead,
  277. StreamWrite,
  278. StreamAvailable,
  279. StreamAvailable64,
  280. StreamSync,
  281. StreamSeek,
  282. StreamSeek64,
  283. StreamFileInfo,
  284. StreamFileInfo64,
  285. StreamWritev,
  286. StreamConnect,
  287. StreamAccept,
  288. StreamBind,
  289. StreamListen,
  290. StreamShutdown,
  291. StreamRecv,
  292. StreamSend,
  293. StreamRecvfrom,
  294. StreamSendto,
  295. StreamPoll,
  296. StreamAcceptRead,
  297. StreamTransmitFile,
  298. StreamGetSockName,
  299. StreamGetPeerName,
  300. StreamReserved,
  301. StreamReserved,
  302. StreamGetSockOption,
  303. StreamSetSockOption,
  304. StreamSendfile,
  305. StreamConnectContinue,
  306. StreamReserved,
  307. StreamReserved,
  308. StreamReserved,
  309. StreamReserved
  310. };
  311. NSSStreamAdapter::NSSStreamAdapter(StreamInterface *stream)
  312. : SSLStreamAdapterHelper(stream),
  313. ssl_fd_(NULL),
  314. cert_ok_(false) {
  315. }
  316. bool NSSStreamAdapter::Init() {
  317. if (nspr_layer_identity == PR_INVALID_IO_LAYER) {
  318. nspr_layer_identity = PR_GetUniqueIdentity("nssstreamadapter");
  319. }
  320. PRFileDesc *pr_fd = PR_CreateIOLayerStub(nspr_layer_identity, &nss_methods);
  321. if (!pr_fd)
  322. return false;
  323. pr_fd->secret = reinterpret_cast<PRFilePrivate *>(stream());
  324. PRFileDesc *ssl_fd;
  325. if (ssl_mode_ == SSL_MODE_DTLS) {
  326. ssl_fd = DTLS_ImportFD(NULL, pr_fd);
  327. } else {
  328. ssl_fd = SSL_ImportFD(NULL, pr_fd);
  329. }
  330. ASSERT(ssl_fd != NULL); // This should never happen
  331. if (!ssl_fd) {
  332. PR_Close(pr_fd);
  333. return false;
  334. }
  335. SECStatus rv;
  336. // Turn on security.
  337. rv = SSL_OptionSet(ssl_fd, SSL_SECURITY, PR_TRUE);
  338. if (rv != SECSuccess) {
  339. LOG(LS_ERROR) << "Error enabling security on SSL Socket";
  340. return false;
  341. }
  342. // Disable SSLv2.
  343. rv = SSL_OptionSet(ssl_fd, SSL_ENABLE_SSL2, PR_FALSE);
  344. if (rv != SECSuccess) {
  345. LOG(LS_ERROR) << "Error disabling SSL2";
  346. return false;
  347. }
  348. // Disable caching.
  349. // TODO(ekr@rtfm.com): restore this when I have the caching
  350. // identity set.
  351. rv = SSL_OptionSet(ssl_fd, SSL_NO_CACHE, PR_TRUE);
  352. if (rv != SECSuccess) {
  353. LOG(LS_ERROR) << "Error disabling cache";
  354. return false;
  355. }
  356. // Disable session tickets.
  357. rv = SSL_OptionSet(ssl_fd, SSL_ENABLE_SESSION_TICKETS, PR_FALSE);
  358. if (rv != SECSuccess) {
  359. LOG(LS_ERROR) << "Error enabling tickets";
  360. return false;
  361. }
  362. // Disable renegotiation.
  363. rv = SSL_OptionSet(ssl_fd, SSL_ENABLE_RENEGOTIATION,
  364. SSL_RENEGOTIATE_NEVER);
  365. if (rv != SECSuccess) {
  366. LOG(LS_ERROR) << "Error disabling renegotiation";
  367. return false;
  368. }
  369. // Disable false start.
  370. rv = SSL_OptionSet(ssl_fd, SSL_ENABLE_FALSE_START, PR_FALSE);
  371. if (rv != SECSuccess) {
  372. LOG(LS_ERROR) << "Error disabling false start";
  373. return false;
  374. }
  375. ssl_fd_ = ssl_fd;
  376. return true;
  377. }
  378. NSSStreamAdapter::~NSSStreamAdapter() {
  379. if (ssl_fd_)
  380. PR_Close(ssl_fd_);
  381. };
  382. int NSSStreamAdapter::BeginSSL() {
  383. SECStatus rv;
  384. if (!Init()) {
  385. Error("Init", -1, false);
  386. return -1;
  387. }
  388. ASSERT(state_ == SSL_CONNECTING);
  389. // The underlying stream has been opened. If we are in peer-to-peer mode
  390. // then a peer certificate must have been specified by now.
  391. ASSERT(!ssl_server_name_.empty() ||
  392. peer_certificate_.get() != NULL ||
  393. !peer_certificate_digest_algorithm_.empty());
  394. LOG(LS_INFO) << "BeginSSL: "
  395. << (!ssl_server_name_.empty() ? ssl_server_name_ :
  396. "with peer");
  397. if (role_ == SSL_CLIENT) {
  398. LOG(LS_INFO) << "BeginSSL: as client";
  399. rv = SSL_GetClientAuthDataHook(ssl_fd_, GetClientAuthDataHook,
  400. this);
  401. if (rv != SECSuccess) {
  402. Error("BeginSSL", -1, false);
  403. return -1;
  404. }
  405. } else {
  406. LOG(LS_INFO) << "BeginSSL: as server";
  407. NSSIdentity *identity;
  408. if (identity_.get()) {
  409. identity = static_cast<NSSIdentity *>(identity_.get());
  410. } else {
  411. LOG(LS_ERROR) << "Can't be an SSL server without an identity";
  412. Error("BeginSSL", -1, false);
  413. return -1;
  414. }
  415. rv = SSL_ConfigSecureServer(ssl_fd_, identity->certificate().certificate(),
  416. identity->keypair()->privkey(),
  417. kt_rsa);
  418. if (rv != SECSuccess) {
  419. Error("BeginSSL", -1, false);
  420. return -1;
  421. }
  422. // Insist on a certificate from the client
  423. rv = SSL_OptionSet(ssl_fd_, SSL_REQUEST_CERTIFICATE, PR_TRUE);
  424. if (rv != SECSuccess) {
  425. Error("BeginSSL", -1, false);
  426. return -1;
  427. }
  428. rv = SSL_OptionSet(ssl_fd_, SSL_REQUIRE_CERTIFICATE, PR_TRUE);
  429. if (rv != SECSuccess) {
  430. Error("BeginSSL", -1, false);
  431. return -1;
  432. }
  433. }
  434. // Set the version range.
  435. SSLVersionRange vrange;
  436. vrange.min = (ssl_mode_ == SSL_MODE_DTLS) ?
  437. SSL_LIBRARY_VERSION_TLS_1_1 :
  438. SSL_LIBRARY_VERSION_TLS_1_0;
  439. vrange.max = SSL_LIBRARY_VERSION_TLS_1_1;
  440. rv = SSL_VersionRangeSet(ssl_fd_, &vrange);
  441. if (rv != SECSuccess) {
  442. Error("BeginSSL", -1, false);
  443. return -1;
  444. }
  445. // SRTP
  446. #ifdef HAVE_DTLS_SRTP
  447. if (!srtp_ciphers_.empty()) {
  448. rv = SSL_SetSRTPCiphers(ssl_fd_, &srtp_ciphers_[0], srtp_ciphers_.size());
  449. if (rv != SECSuccess) {
  450. Error("BeginSSL", -1, false);
  451. return -1;
  452. }
  453. }
  454. #endif
  455. // Certificate validation
  456. rv = SSL_AuthCertificateHook(ssl_fd_, AuthCertificateHook, this);
  457. if (rv != SECSuccess) {
  458. Error("BeginSSL", -1, false);
  459. return -1;
  460. }
  461. // Now start the handshake
  462. rv = SSL_ResetHandshake(ssl_fd_, role_ == SSL_SERVER ? PR_TRUE : PR_FALSE);
  463. if (rv != SECSuccess) {
  464. Error("BeginSSL", -1, false);
  465. return -1;
  466. }
  467. return ContinueSSL();
  468. }
  469. int NSSStreamAdapter::ContinueSSL() {
  470. LOG(LS_INFO) << "ContinueSSL";
  471. ASSERT(state_ == SSL_CONNECTING);
  472. // Clear the DTLS timer
  473. Thread::Current()->Clear(this, MSG_DTLS_TIMEOUT);
  474. SECStatus rv = SSL_ForceHandshake(ssl_fd_);
  475. if (rv == SECSuccess) {
  476. LOG(LS_INFO) << "Handshake complete";
  477. ASSERT(cert_ok_);
  478. if (!cert_ok_) {
  479. Error("ContinueSSL", -1, true);
  480. return -1;
  481. }
  482. state_ = SSL_CONNECTED;
  483. StreamAdapterInterface::OnEvent(stream(), SE_OPEN|SE_READ|SE_WRITE, 0);
  484. return 0;
  485. }
  486. PRInt32 err = PR_GetError();
  487. switch (err) {
  488. case SSL_ERROR_RX_MALFORMED_HANDSHAKE:
  489. if (ssl_mode_ != SSL_MODE_DTLS) {
  490. Error("ContinueSSL", -1, true);
  491. return -1;
  492. } else {
  493. LOG(LS_INFO) << "Malformed DTLS message. Ignoring.";
  494. // Fall through
  495. }
  496. case PR_WOULD_BLOCK_ERROR:
  497. LOG(LS_INFO) << "Would have blocked";
  498. if (ssl_mode_ == SSL_MODE_DTLS) {
  499. PRIntervalTime timeout;
  500. SECStatus rv = DTLS_GetHandshakeTimeout(ssl_fd_, &timeout);
  501. if (rv == SECSuccess) {
  502. LOG(LS_INFO) << "Timeout is " << timeout << " ms";
  503. Thread::Current()->PostDelayed(PR_IntervalToMilliseconds(timeout),
  504. this, MSG_DTLS_TIMEOUT, 0);
  505. }
  506. }
  507. return 0;
  508. default:
  509. LOG(LS_INFO) << "Error " << err;
  510. break;
  511. }
  512. Error("ContinueSSL", -1, true);
  513. return -1;
  514. }
  515. void NSSStreamAdapter::Cleanup() {
  516. if (state_ != SSL_ERROR) {
  517. state_ = SSL_CLOSED;
  518. }
  519. if (ssl_fd_) {
  520. PR_Close(ssl_fd_);
  521. ssl_fd_ = NULL;
  522. }
  523. identity_.reset();
  524. peer_certificate_.reset();
  525. Thread::Current()->Clear(this, MSG_DTLS_TIMEOUT);
  526. }
  527. StreamResult NSSStreamAdapter::Read(void* data, size_t data_len,
  528. size_t* read, int* error) {
  529. // SSL_CONNECTED sanity check.
  530. switch (state_) {
  531. case SSL_NONE:
  532. case SSL_WAIT:
  533. case SSL_CONNECTING:
  534. return SR_BLOCK;
  535. case SSL_CONNECTED:
  536. break;
  537. case SSL_CLOSED:
  538. return SR_EOS;
  539. case SSL_ERROR:
  540. default:
  541. if (error)
  542. *error = ssl_error_code_;
  543. return SR_ERROR;
  544. }
  545. PRInt32 rv = PR_Read(ssl_fd_, data, data_len);
  546. if (rv == 0) {
  547. return SR_EOS;
  548. }
  549. // Error
  550. if (rv < 0) {
  551. PRInt32 err = PR_GetError();
  552. switch (err) {
  553. case PR_WOULD_BLOCK_ERROR:
  554. return SR_BLOCK;
  555. default:
  556. Error("Read", -1, false);
  557. *error = err; // libjingle semantics are that this is impl-specific
  558. return SR_ERROR;
  559. }
  560. }
  561. // Success
  562. *read = rv;
  563. return SR_SUCCESS;
  564. }
  565. StreamResult NSSStreamAdapter::Write(const void* data, size_t data_len,
  566. size_t* written, int* error) {
  567. // SSL_CONNECTED sanity check.
  568. switch (state_) {
  569. case SSL_NONE:
  570. case SSL_WAIT:
  571. case SSL_CONNECTING:
  572. return SR_BLOCK;
  573. case SSL_CONNECTED:
  574. break;
  575. case SSL_ERROR:
  576. case SSL_CLOSED:
  577. default:
  578. if (error)
  579. *error = ssl_error_code_;
  580. return SR_ERROR;
  581. }
  582. PRInt32 rv = PR_Write(ssl_fd_, data, data_len);
  583. // Error
  584. if (rv < 0) {
  585. PRInt32 err = PR_GetError();
  586. switch (err) {
  587. case PR_WOULD_BLOCK_ERROR:
  588. return SR_BLOCK;
  589. default:
  590. Error("Write", -1, false);
  591. *error = err; // libjingle semantics are that this is impl-specific
  592. return SR_ERROR;
  593. }
  594. }
  595. // Success
  596. *written = rv;
  597. return SR_SUCCESS;
  598. }
  599. void NSSStreamAdapter::OnEvent(StreamInterface* stream, int events,
  600. int err) {
  601. int events_to_signal = 0;
  602. int signal_error = 0;
  603. ASSERT(stream == this->stream());
  604. if ((events & SE_OPEN)) {
  605. LOG(LS_INFO) << "NSSStreamAdapter::OnEvent SE_OPEN";
  606. if (state_ != SSL_WAIT) {
  607. ASSERT(state_ == SSL_NONE);
  608. events_to_signal |= SE_OPEN;
  609. } else {
  610. state_ = SSL_CONNECTING;
  611. if (int err = BeginSSL()) {
  612. Error("BeginSSL", err, true);
  613. return;
  614. }
  615. }
  616. }
  617. if ((events & (SE_READ|SE_WRITE))) {
  618. LOG(LS_INFO) << "NSSStreamAdapter::OnEvent"
  619. << ((events & SE_READ) ? " SE_READ" : "")
  620. << ((events & SE_WRITE) ? " SE_WRITE" : "");
  621. if (state_ == SSL_NONE) {
  622. events_to_signal |= events & (SE_READ|SE_WRITE);
  623. } else if (state_ == SSL_CONNECTING) {
  624. if (int err = ContinueSSL()) {
  625. Error("ContinueSSL", err, true);
  626. return;
  627. }
  628. } else if (state_ == SSL_CONNECTED) {
  629. if (events & SE_WRITE) {
  630. LOG(LS_INFO) << " -- onStreamWriteable";
  631. events_to_signal |= SE_WRITE;
  632. }
  633. if (events & SE_READ) {
  634. LOG(LS_INFO) << " -- onStreamReadable";
  635. events_to_signal |= SE_READ;
  636. }
  637. }
  638. }
  639. if ((events & SE_CLOSE)) {
  640. LOG(LS_INFO) << "NSSStreamAdapter::OnEvent(SE_CLOSE, " << err << ")";
  641. Cleanup();
  642. events_to_signal |= SE_CLOSE;
  643. // SE_CLOSE is the only event that uses the final parameter to OnEvent().
  644. ASSERT(signal_error == 0);
  645. signal_error = err;
  646. }
  647. if (events_to_signal)
  648. StreamAdapterInterface::OnEvent(stream, events_to_signal, signal_error);
  649. }
  650. void NSSStreamAdapter::OnMessage(Message* msg) {
  651. // Process our own messages and then pass others to the superclass
  652. if (MSG_DTLS_TIMEOUT == msg->message_id) {
  653. LOG(LS_INFO) << "DTLS timeout expired";
  654. ContinueSSL();
  655. } else {
  656. StreamInterface::OnMessage(msg);
  657. }
  658. }
  659. // Certificate verification callback. Called to check any certificate
  660. SECStatus NSSStreamAdapter::AuthCertificateHook(void *arg,
  661. PRFileDesc *fd,
  662. PRBool checksig,
  663. PRBool isServer) {
  664. LOG(LS_INFO) << "NSSStreamAdapter::AuthCertificateHook";
  665. NSSCertificate peer_cert(SSL_PeerCertificate(fd));
  666. bool ok = false;
  667. // TODO(ekr@rtfm.com): Should we be enforcing self-signed like
  668. // the OpenSSL version?
  669. NSSStreamAdapter *stream = reinterpret_cast<NSSStreamAdapter *>(arg);
  670. if (stream->peer_certificate_.get()) {
  671. LOG(LS_INFO) << "Checking against specified certificate";
  672. // The peer certificate was specified
  673. if (reinterpret_cast<NSSCertificate *>(stream->peer_certificate_.get())->
  674. Equals(&peer_cert)) {
  675. LOG(LS_INFO) << "Accepted peer certificate";
  676. ok = true;
  677. }
  678. } else if (!stream->peer_certificate_digest_algorithm_.empty()) {
  679. LOG(LS_INFO) << "Checking against specified digest";
  680. // The peer certificate digest was specified
  681. unsigned char digest[64]; // Maximum size
  682. std::size_t digest_length;
  683. if (!peer_cert.ComputeDigest(
  684. stream->peer_certificate_digest_algorithm_,
  685. digest, sizeof(digest), &digest_length)) {
  686. LOG(LS_ERROR) << "Digest computation failed";
  687. } else {
  688. Buffer computed_digest(digest, digest_length);
  689. if (computed_digest == stream->peer_certificate_digest_value_) {
  690. LOG(LS_INFO) << "Accepted peer certificate";
  691. ok = true;
  692. }
  693. }
  694. } else {
  695. // Other modes, but we haven't implemented yet
  696. // TODO(ekr@rtfm.com): Implement real certificate validation
  697. UNIMPLEMENTED;
  698. }
  699. if (ok) {
  700. stream->cert_ok_ = true;
  701. return SECSuccess;
  702. }
  703. if (!ok && stream->ignore_bad_cert()) {
  704. LOG(LS_WARNING) << "Ignoring cert error while verifying cert chain";
  705. stream->cert_ok_ = true;
  706. return SECSuccess;
  707. }
  708. PORT_SetError(SEC_ERROR_UNTRUSTED_CERT);
  709. return SECFailure;
  710. }
  711. SECStatus NSSStreamAdapter::GetClientAuthDataHook(void *arg, PRFileDesc *fd,
  712. CERTDistNames *caNames,
  713. CERTCertificate **pRetCert,
  714. SECKEYPrivateKey **pRetKey) {
  715. LOG(LS_INFO) << "Client cert requested";
  716. NSSStreamAdapter *stream = reinterpret_cast<NSSStreamAdapter *>(arg);
  717. if (!stream->identity_.get()) {
  718. LOG(LS_ERROR) << "No identity available";
  719. return SECFailure;
  720. }
  721. NSSIdentity *identity = static_cast<NSSIdentity *>(stream->identity_.get());
  722. // Destroyed internally by NSS
  723. *pRetCert = CERT_DupCertificate(identity->certificate().certificate());
  724. *pRetKey = SECKEY_CopyPrivateKey(identity->keypair()->privkey());
  725. return SECSuccess;
  726. }
  727. // RFC 5705 Key Exporter
  728. bool NSSStreamAdapter::ExportKeyingMaterial(const std::string& label,
  729. const uint8* context,
  730. size_t context_len,
  731. bool use_context,
  732. uint8* result,
  733. size_t result_len) {
  734. SECStatus rv = SSL_ExportKeyingMaterial(ssl_fd_,
  735. label.c_str(), label.size(),
  736. use_context,
  737. context, context_len,
  738. result, result_len);
  739. return rv == SECSuccess;
  740. }
  741. bool NSSStreamAdapter::SetDtlsSrtpCiphers(
  742. const std::vector<std::string>& ciphers) {
  743. #ifdef HAVE_DTLS_SRTP
  744. std::vector<PRUint16> internal_ciphers;
  745. if (state_ != SSL_NONE)
  746. return false;
  747. for (std::vector<std::string>::const_iterator cipher = ciphers.begin();
  748. cipher != ciphers.end(); ++cipher) {
  749. bool found = false;
  750. for (const SrtpCipherMapEntry *entry = kSrtpCipherMap; entry->cipher_id;
  751. ++entry) {
  752. if (*cipher == entry->external_name) {
  753. found = true;
  754. internal_ciphers.push_back(entry->cipher_id);
  755. break;
  756. }
  757. }
  758. if (!found) {
  759. LOG(LS_ERROR) << "Could not find cipher: " << *cipher;
  760. return false;
  761. }
  762. }
  763. if (internal_ciphers.empty())
  764. return false;
  765. srtp_ciphers_ = internal_ciphers;
  766. return true;
  767. #else
  768. return false;
  769. #endif
  770. }
  771. bool NSSStreamAdapter::GetDtlsSrtpCipher(std::string* cipher) {
  772. #ifdef HAVE_DTLS_SRTP
  773. ASSERT(state_ == SSL_CONNECTED);
  774. if (state_ != SSL_CONNECTED)
  775. return false;
  776. PRUint16 selected_cipher;
  777. SECStatus rv = SSL_GetSRTPCipher(ssl_fd_, &selected_cipher);
  778. if (rv == SECFailure)
  779. return false;
  780. for (const SrtpCipherMapEntry *entry = kSrtpCipherMap;
  781. entry->cipher_id; ++entry) {
  782. if (selected_cipher == entry->cipher_id) {
  783. *cipher = entry->external_name;
  784. return true;
  785. }
  786. }
  787. ASSERT(false); // This should never happen
  788. #endif
  789. return false;
  790. }
  791. bool NSSContext::initialized;
  792. NSSContext *NSSContext::global_nss_context;
  793. // Static initialization and shutdown
  794. NSSContext *NSSContext::Instance() {
  795. if (!global_nss_context) {
  796. NSSContext *new_ctx = new NSSContext();
  797. if (!(new_ctx->slot_ = PK11_GetInternalSlot())) {
  798. delete new_ctx;
  799. goto fail;
  800. }
  801. global_nss_context = new_ctx;
  802. }
  803. fail:
  804. return global_nss_context;
  805. }
  806. bool NSSContext::InitializeSSL(VerificationCallback callback) {
  807. ASSERT(!callback);
  808. if (!initialized) {
  809. SECStatus rv;
  810. rv = NSS_NoDB_Init(NULL);
  811. if (rv != SECSuccess) {
  812. LOG(LS_ERROR) << "Couldn't initialize NSS error=" <<
  813. PORT_GetError();
  814. return false;
  815. }
  816. NSS_SetDomesticPolicy();
  817. initialized = true;
  818. }
  819. return true;
  820. }
  821. bool NSSContext::InitializeSSLThread() {
  822. // Not needed
  823. return true;
  824. }
  825. bool NSSContext::CleanupSSL() {
  826. // Not needed
  827. return true;
  828. }
  829. bool NSSStreamAdapter::HaveDtls() {
  830. return true;
  831. }
  832. bool NSSStreamAdapter::HaveDtlsSrtp() {
  833. #ifdef HAVE_DTLS_SRTP
  834. return true;
  835. #else
  836. return false;
  837. #endif
  838. }
  839. bool NSSStreamAdapter::HaveExporter() {
  840. return true;
  841. }
  842. } // namespace talk_base
  843. #endif // HAVE_NSS_SSL_H