/security/nss/lib/ssl/sslsecur.c

http://github.com/zpao/v8monkey · C · 1536 lines · 1056 code · 198 blank · 282 comment · 257 complexity · aeaf6ce171c6dbd5f44180f55370deec MD5 · raw file

  1. /*
  2. * Various SSL functions.
  3. *
  4. * ***** BEGIN LICENSE BLOCK *****
  5. * Version: MPL 1.1/GPL 2.0/LGPL 2.1
  6. *
  7. * The contents of this file are subject to the Mozilla Public License Version
  8. * 1.1 (the "License"); you may not use this file except in compliance with
  9. * the License. You may obtain a copy of the License at
  10. * http://www.mozilla.org/MPL/
  11. *
  12. * Software distributed under the License is distributed on an "AS IS" basis,
  13. * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  14. * for the specific language governing rights and limitations under the
  15. * License.
  16. *
  17. * The Original Code is the Netscape security libraries.
  18. *
  19. * The Initial Developer of the Original Code is
  20. * Netscape Communications Corporation.
  21. * Portions created by the Initial Developer are Copyright (C) 1994-2000
  22. * the Initial Developer. All Rights Reserved.
  23. *
  24. * Contributor(s):
  25. * Dr Vipul Gupta <vipul.gupta@sun.com>, Sun Microsystems Laboratories
  26. *
  27. * Alternatively, the contents of this file may be used under the terms of
  28. * either the GNU General Public License Version 2 or later (the "GPL"), or
  29. * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
  30. * in which case the provisions of the GPL or the LGPL are applicable instead
  31. * of those above. If you wish to allow use of your version of this file only
  32. * under the terms of either the GPL or the LGPL, and not to allow others to
  33. * use your version of this file under the terms of the MPL, indicate your
  34. * decision by deleting the provisions above and replace them with the notice
  35. * and other provisions required by the GPL or the LGPL. If you do not delete
  36. * the provisions above, a recipient may use your version of this file under
  37. * the terms of any one of the MPL, the GPL or the LGPL.
  38. *
  39. * ***** END LICENSE BLOCK ***** */
  40. /* $Id: sslsecur.c,v 1.56 2012/02/11 12:58:47 kaie%kuix.de Exp $ */
  41. #include "cert.h"
  42. #include "secitem.h"
  43. #include "keyhi.h"
  44. #include "ssl.h"
  45. #include "sslimpl.h"
  46. #include "sslproto.h"
  47. #include "secoid.h" /* for SECOID_GetALgorithmTag */
  48. #include "pk11func.h" /* for PK11_GenerateRandom */
  49. #include "nss.h" /* for NSS_RegisterShutdown */
  50. #include "prinit.h" /* for PR_CallOnceWithArg */
  51. #define MAX_BLOCK_CYPHER_SIZE 32
  52. #define TEST_FOR_FAILURE /* reminder */
  53. #define SET_ERROR_CODE /* reminder */
  54. /* Returns a SECStatus: SECSuccess or SECFailure, NOT SECWouldBlock.
  55. *
  56. * Currently, the list of functions called through ss->handshake is:
  57. *
  58. * In sslsocks.c:
  59. * SocksGatherRecord
  60. * SocksHandleReply
  61. * SocksStartGather
  62. *
  63. * In sslcon.c:
  64. * ssl_GatherRecord1stHandshake
  65. * ssl2_HandleClientSessionKeyMessage
  66. * ssl2_HandleMessage
  67. * ssl2_HandleVerifyMessage
  68. * ssl2_BeginClientHandshake
  69. * ssl2_BeginServerHandshake
  70. * ssl2_HandleClientHelloMessage
  71. * ssl2_HandleServerHelloMessage
  72. *
  73. * The ss->handshake function returns SECWouldBlock under these conditions:
  74. * 1. ssl_GatherRecord1stHandshake called ssl2_GatherData which read in
  75. * the beginning of an SSL v3 hello message and returned SECWouldBlock
  76. * to switch to SSL v3 handshake processing.
  77. *
  78. * 2. ssl2_HandleClientHelloMessage discovered version 3.0 in the incoming
  79. * v2 client hello msg, and called ssl3_HandleV2ClientHello which
  80. * returned SECWouldBlock.
  81. *
  82. * 3. SECWouldBlock was returned by one of the callback functions, via
  83. * one of these paths:
  84. * - ssl2_HandleMessage() -> ssl2_HandleRequestCertificate() ->
  85. * ss->getClientAuthData()
  86. *
  87. * - ssl2_HandleServerHelloMessage() -> ss->handleBadCert()
  88. *
  89. * - ssl_GatherRecord1stHandshake() -> ssl3_GatherCompleteHandshake() ->
  90. * ssl3_HandleRecord() -> ssl3_HandleHandshake() ->
  91. * ssl3_HandleHandshakeMessage() -> ssl3_HandleCertificate() ->
  92. * ss->handleBadCert()
  93. *
  94. * - ssl_GatherRecord1stHandshake() -> ssl3_GatherCompleteHandshake() ->
  95. * ssl3_HandleRecord() -> ssl3_HandleHandshake() ->
  96. * ssl3_HandleHandshakeMessage() -> ssl3_HandleCertificateRequest() ->
  97. * ss->getClientAuthData()
  98. *
  99. * Called from: SSL_ForceHandshake (below),
  100. * ssl_SecureRecv (below) and
  101. * ssl_SecureSend (below)
  102. * from: WaitForResponse in sslsocks.c
  103. * ssl_SocksRecv in sslsocks.c
  104. * ssl_SocksSend in sslsocks.c
  105. *
  106. * Caller must hold the (write) handshakeLock.
  107. */
  108. int
  109. ssl_Do1stHandshake(sslSocket *ss)
  110. {
  111. int rv = SECSuccess;
  112. int loopCount = 0;
  113. do {
  114. PORT_Assert(ss->opt.noLocks || ssl_Have1stHandshakeLock(ss) );
  115. PORT_Assert(ss->opt.noLocks || !ssl_HaveRecvBufLock(ss));
  116. PORT_Assert(ss->opt.noLocks || !ssl_HaveXmitBufLock(ss));
  117. PORT_Assert(ss->opt.noLocks || !ssl_HaveSSL3HandshakeLock(ss));
  118. if (ss->handshake == 0) {
  119. /* Previous handshake finished. Switch to next one */
  120. ss->handshake = ss->nextHandshake;
  121. ss->nextHandshake = 0;
  122. }
  123. if (ss->handshake == 0) {
  124. /* Previous handshake finished. Switch to security handshake */
  125. ss->handshake = ss->securityHandshake;
  126. ss->securityHandshake = 0;
  127. }
  128. if (ss->handshake == 0) {
  129. ssl_GetRecvBufLock(ss);
  130. ss->gs.recordLen = 0;
  131. ssl_ReleaseRecvBufLock(ss);
  132. SSL_TRC(3, ("%d: SSL[%d]: handshake is completed",
  133. SSL_GETPID(), ss->fd));
  134. /* call handshake callback for ssl v2 */
  135. /* for v3 this is done in ssl3_HandleFinished() */
  136. if ((ss->handshakeCallback != NULL) && /* has callback */
  137. (!ss->firstHsDone) && /* only first time */
  138. (ss->version < SSL_LIBRARY_VERSION_3_0)) { /* not ssl3 */
  139. ss->firstHsDone = PR_TRUE;
  140. (ss->handshakeCallback)(ss->fd, ss->handshakeCallbackData);
  141. }
  142. ss->firstHsDone = PR_TRUE;
  143. ss->gs.writeOffset = 0;
  144. ss->gs.readOffset = 0;
  145. break;
  146. }
  147. rv = (*ss->handshake)(ss);
  148. ++loopCount;
  149. /* This code must continue to loop on SECWouldBlock,
  150. * or any positive value. See XXX_1 comments.
  151. */
  152. } while (rv != SECFailure); /* was (rv >= 0); XXX_1 */
  153. PORT_Assert(ss->opt.noLocks || !ssl_HaveRecvBufLock(ss));
  154. PORT_Assert(ss->opt.noLocks || !ssl_HaveXmitBufLock(ss));
  155. PORT_Assert(ss->opt.noLocks || !ssl_HaveSSL3HandshakeLock(ss));
  156. if (rv == SECWouldBlock) {
  157. PORT_SetError(PR_WOULD_BLOCK_ERROR);
  158. rv = SECFailure;
  159. }
  160. return rv;
  161. }
  162. /*
  163. * Handshake function that blocks. Used to force a
  164. * retry on a connection on the next read/write.
  165. */
  166. static SECStatus
  167. ssl3_AlwaysBlock(sslSocket *ss)
  168. {
  169. PORT_SetError(PR_WOULD_BLOCK_ERROR); /* perhaps redundant. */
  170. return SECWouldBlock;
  171. }
  172. /*
  173. * set the initial handshake state machine to block
  174. */
  175. void
  176. ssl3_SetAlwaysBlock(sslSocket *ss)
  177. {
  178. if (!ss->firstHsDone) {
  179. ss->handshake = ssl3_AlwaysBlock;
  180. ss->nextHandshake = 0;
  181. }
  182. }
  183. static SECStatus
  184. ssl_SetTimeout(PRFileDesc *fd, PRIntervalTime timeout)
  185. {
  186. sslSocket *ss;
  187. ss = ssl_FindSocket(fd);
  188. if (!ss) {
  189. SSL_DBG(("%d: SSL[%d]: bad socket in SetTimeout", SSL_GETPID(), fd));
  190. return SECFailure;
  191. }
  192. SSL_LOCK_READER(ss);
  193. ss->rTimeout = timeout;
  194. if (ss->opt.fdx) {
  195. SSL_LOCK_WRITER(ss);
  196. }
  197. ss->wTimeout = timeout;
  198. if (ss->opt.fdx) {
  199. SSL_UNLOCK_WRITER(ss);
  200. }
  201. SSL_UNLOCK_READER(ss);
  202. return SECSuccess;
  203. }
  204. /* Acquires and releases HandshakeLock.
  205. */
  206. SECStatus
  207. SSL_ResetHandshake(PRFileDesc *s, PRBool asServer)
  208. {
  209. sslSocket *ss;
  210. SECStatus status;
  211. PRNetAddr addr;
  212. ss = ssl_FindSocket(s);
  213. if (!ss) {
  214. SSL_DBG(("%d: SSL[%d]: bad socket in ResetHandshake", SSL_GETPID(), s));
  215. return SECFailure;
  216. }
  217. /* Don't waste my time */
  218. if (!ss->opt.useSecurity)
  219. return SECSuccess;
  220. SSL_LOCK_READER(ss);
  221. SSL_LOCK_WRITER(ss);
  222. /* Reset handshake state */
  223. ssl_Get1stHandshakeLock(ss);
  224. ss->firstHsDone = PR_FALSE;
  225. if ( asServer ) {
  226. ss->handshake = ssl2_BeginServerHandshake;
  227. ss->handshaking = sslHandshakingAsServer;
  228. } else {
  229. ss->handshake = ssl2_BeginClientHandshake;
  230. ss->handshaking = sslHandshakingAsClient;
  231. }
  232. ss->nextHandshake = 0;
  233. ss->securityHandshake = 0;
  234. ssl_GetRecvBufLock(ss);
  235. status = ssl_InitGather(&ss->gs);
  236. ssl_ReleaseRecvBufLock(ss);
  237. ssl_GetSSL3HandshakeLock(ss);
  238. /*
  239. ** Blow away old security state and get a fresh setup.
  240. */
  241. ssl_GetXmitBufLock(ss);
  242. ssl_ResetSecurityInfo(&ss->sec, PR_TRUE);
  243. status = ssl_CreateSecurityInfo(ss);
  244. ssl_ReleaseXmitBufLock(ss);
  245. ssl_ReleaseSSL3HandshakeLock(ss);
  246. ssl_Release1stHandshakeLock(ss);
  247. if (!ss->TCPconnected)
  248. ss->TCPconnected = (PR_SUCCESS == ssl_DefGetpeername(ss, &addr));
  249. SSL_UNLOCK_WRITER(ss);
  250. SSL_UNLOCK_READER(ss);
  251. return status;
  252. }
  253. /* For SSLv2, does nothing but return an error.
  254. ** For SSLv3, flushes SID cache entry (if requested),
  255. ** and then starts new client hello or hello request.
  256. ** Acquires and releases HandshakeLock.
  257. */
  258. SECStatus
  259. SSL_ReHandshake(PRFileDesc *fd, PRBool flushCache)
  260. {
  261. sslSocket *ss;
  262. SECStatus rv;
  263. ss = ssl_FindSocket(fd);
  264. if (!ss) {
  265. SSL_DBG(("%d: SSL[%d]: bad socket in RedoHandshake", SSL_GETPID(), fd));
  266. return SECFailure;
  267. }
  268. if (!ss->opt.useSecurity)
  269. return SECSuccess;
  270. ssl_Get1stHandshakeLock(ss);
  271. /* SSL v2 protocol does not support subsequent handshakes. */
  272. if (ss->version < SSL_LIBRARY_VERSION_3_0) {
  273. PORT_SetError(SEC_ERROR_INVALID_ARGS);
  274. rv = SECFailure;
  275. } else {
  276. ssl_GetSSL3HandshakeLock(ss);
  277. rv = ssl3_RedoHandshake(ss, flushCache); /* force full handshake. */
  278. ssl_ReleaseSSL3HandshakeLock(ss);
  279. }
  280. ssl_Release1stHandshakeLock(ss);
  281. return rv;
  282. }
  283. /*
  284. ** Same as above, but with an I/O timeout.
  285. */
  286. SSL_IMPORT SECStatus SSL_ReHandshakeWithTimeout(PRFileDesc *fd,
  287. PRBool flushCache,
  288. PRIntervalTime timeout)
  289. {
  290. if (SECSuccess != ssl_SetTimeout(fd, timeout)) {
  291. return SECFailure;
  292. }
  293. return SSL_ReHandshake(fd, flushCache);
  294. }
  295. SECStatus
  296. SSL_RedoHandshake(PRFileDesc *fd)
  297. {
  298. return SSL_ReHandshake(fd, PR_TRUE);
  299. }
  300. /* Register an application callback to be called when SSL handshake completes.
  301. ** Acquires and releases HandshakeLock.
  302. */
  303. SECStatus
  304. SSL_HandshakeCallback(PRFileDesc *fd, SSLHandshakeCallback cb,
  305. void *client_data)
  306. {
  307. sslSocket *ss;
  308. ss = ssl_FindSocket(fd);
  309. if (!ss) {
  310. SSL_DBG(("%d: SSL[%d]: bad socket in HandshakeCallback",
  311. SSL_GETPID(), fd));
  312. return SECFailure;
  313. }
  314. if (!ss->opt.useSecurity) {
  315. PORT_SetError(SEC_ERROR_INVALID_ARGS);
  316. return SECFailure;
  317. }
  318. ssl_Get1stHandshakeLock(ss);
  319. ssl_GetSSL3HandshakeLock(ss);
  320. ss->handshakeCallback = cb;
  321. ss->handshakeCallbackData = client_data;
  322. ssl_ReleaseSSL3HandshakeLock(ss);
  323. ssl_Release1stHandshakeLock(ss);
  324. return SECSuccess;
  325. }
  326. /* Try to make progress on an SSL handshake by attempting to read the
  327. ** next handshake from the peer, and sending any responses.
  328. ** For non-blocking sockets, returns PR_ERROR_WOULD_BLOCK if it cannot
  329. ** read the next handshake from the underlying socket.
  330. ** For SSLv2, returns when handshake is complete or fatal error occurs.
  331. ** For SSLv3, returns when handshake is complete, or application data has
  332. ** arrived that must be taken by application before handshake can continue,
  333. ** or a fatal error occurs.
  334. ** Application should use handshake completion callback to tell which.
  335. */
  336. SECStatus
  337. SSL_ForceHandshake(PRFileDesc *fd)
  338. {
  339. sslSocket *ss;
  340. SECStatus rv = SECFailure;
  341. ss = ssl_FindSocket(fd);
  342. if (!ss) {
  343. SSL_DBG(("%d: SSL[%d]: bad socket in ForceHandshake",
  344. SSL_GETPID(), fd));
  345. return rv;
  346. }
  347. /* Don't waste my time */
  348. if (!ss->opt.useSecurity)
  349. return SECSuccess;
  350. if (!ssl_SocketIsBlocking(ss)) {
  351. ssl_GetXmitBufLock(ss);
  352. if (ss->pendingBuf.len != 0) {
  353. int sent = ssl_SendSavedWriteData(ss);
  354. if ((sent < 0) && (PORT_GetError() != PR_WOULD_BLOCK_ERROR)) {
  355. ssl_ReleaseXmitBufLock(ss);
  356. return SECFailure;
  357. }
  358. }
  359. ssl_ReleaseXmitBufLock(ss);
  360. }
  361. ssl_Get1stHandshakeLock(ss);
  362. if (ss->version >= SSL_LIBRARY_VERSION_3_0) {
  363. int gatherResult;
  364. ssl_GetRecvBufLock(ss);
  365. gatherResult = ssl3_GatherCompleteHandshake(ss, 0);
  366. ssl_ReleaseRecvBufLock(ss);
  367. if (gatherResult > 0) {
  368. rv = SECSuccess;
  369. } else if (gatherResult == 0) {
  370. PORT_SetError(PR_END_OF_FILE_ERROR);
  371. } else if (gatherResult == SECWouldBlock) {
  372. PORT_SetError(PR_WOULD_BLOCK_ERROR);
  373. }
  374. } else if (!ss->firstHsDone) {
  375. rv = ssl_Do1stHandshake(ss);
  376. } else {
  377. /* tried to force handshake on an SSL 2 socket that has
  378. ** already completed the handshake. */
  379. rv = SECSuccess; /* just pretend we did it. */
  380. }
  381. ssl_Release1stHandshakeLock(ss);
  382. return rv;
  383. }
  384. /*
  385. ** Same as above, but with an I/O timeout.
  386. */
  387. SSL_IMPORT SECStatus SSL_ForceHandshakeWithTimeout(PRFileDesc *fd,
  388. PRIntervalTime timeout)
  389. {
  390. if (SECSuccess != ssl_SetTimeout(fd, timeout)) {
  391. return SECFailure;
  392. }
  393. return SSL_ForceHandshake(fd);
  394. }
  395. /************************************************************************/
  396. /*
  397. ** Grow a buffer to hold newLen bytes of data.
  398. ** Called for both recv buffers and xmit buffers.
  399. ** Caller must hold xmitBufLock or recvBufLock, as appropriate.
  400. */
  401. SECStatus
  402. sslBuffer_Grow(sslBuffer *b, unsigned int newLen)
  403. {
  404. newLen = PR_MAX(newLen, MAX_FRAGMENT_LENGTH + 2048);
  405. if (newLen > b->space) {
  406. unsigned char *newBuf;
  407. if (b->buf) {
  408. newBuf = (unsigned char *) PORT_Realloc(b->buf, newLen);
  409. } else {
  410. newBuf = (unsigned char *) PORT_Alloc(newLen);
  411. }
  412. if (!newBuf) {
  413. return SECFailure;
  414. }
  415. SSL_TRC(10, ("%d: SSL: grow buffer from %d to %d",
  416. SSL_GETPID(), b->space, newLen));
  417. b->buf = newBuf;
  418. b->space = newLen;
  419. }
  420. return SECSuccess;
  421. }
  422. SECStatus
  423. sslBuffer_Append(sslBuffer *b, const void * data, unsigned int len)
  424. {
  425. unsigned int newLen = b->len + len;
  426. SECStatus rv;
  427. rv = sslBuffer_Grow(b, newLen);
  428. if (rv != SECSuccess)
  429. return rv;
  430. PORT_Memcpy(b->buf + b->len, data, len);
  431. b->len += len;
  432. return SECSuccess;
  433. }
  434. /*
  435. ** Save away write data that is trying to be written before the security
  436. ** handshake has been completed. When the handshake is completed, we will
  437. ** flush this data out.
  438. ** Caller must hold xmitBufLock
  439. */
  440. SECStatus
  441. ssl_SaveWriteData(sslSocket *ss, const void *data, unsigned int len)
  442. {
  443. SECStatus rv;
  444. PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) );
  445. rv = sslBuffer_Append(&ss->pendingBuf, data, len);
  446. SSL_TRC(5, ("%d: SSL[%d]: saving %u bytes of data (%u total saved so far)",
  447. SSL_GETPID(), ss->fd, len, ss->pendingBuf.len));
  448. return rv;
  449. }
  450. /*
  451. ** Send saved write data. This will flush out data sent prior to a
  452. ** complete security handshake. Hopefully there won't be too much of it.
  453. ** Returns count of the bytes sent, NOT a SECStatus.
  454. ** Caller must hold xmitBufLock
  455. */
  456. int
  457. ssl_SendSavedWriteData(sslSocket *ss)
  458. {
  459. int rv = 0;
  460. PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) );
  461. if (ss->pendingBuf.len != 0) {
  462. SSL_TRC(5, ("%d: SSL[%d]: sending %d bytes of saved data",
  463. SSL_GETPID(), ss->fd, ss->pendingBuf.len));
  464. rv = ssl_DefSend(ss, ss->pendingBuf.buf, ss->pendingBuf.len, 0);
  465. if (rv < 0) {
  466. return rv;
  467. }
  468. ss->pendingBuf.len -= rv;
  469. if (ss->pendingBuf.len > 0 && rv > 0) {
  470. /* UGH !! This shifts the whole buffer down by copying it */
  471. PORT_Memmove(ss->pendingBuf.buf, ss->pendingBuf.buf + rv,
  472. ss->pendingBuf.len);
  473. }
  474. }
  475. return rv;
  476. }
  477. /************************************************************************/
  478. /*
  479. ** Receive some application data on a socket. Reads SSL records from the input
  480. ** stream, decrypts them and then copies them to the output buffer.
  481. ** Called from ssl_SecureRecv() below.
  482. **
  483. ** Caller does NOT hold 1stHandshakeLock because that handshake is over.
  484. ** Caller doesn't call this until initial handshake is complete.
  485. ** For SSLv2, there is no subsequent handshake.
  486. ** For SSLv3, the call to ssl3_GatherAppDataRecord may encounter handshake
  487. ** messages from a subsequent handshake.
  488. **
  489. ** This code is similar to, and easily confused with,
  490. ** ssl_GatherRecord1stHandshake() in sslcon.c
  491. */
  492. static int
  493. DoRecv(sslSocket *ss, unsigned char *out, int len, int flags)
  494. {
  495. int rv;
  496. int amount;
  497. int available;
  498. ssl_GetRecvBufLock(ss);
  499. available = ss->gs.writeOffset - ss->gs.readOffset;
  500. if (available == 0) {
  501. /* Get some more data */
  502. if (ss->version >= SSL_LIBRARY_VERSION_3_0) {
  503. /* Wait for application data to arrive. */
  504. rv = ssl3_GatherAppDataRecord(ss, 0);
  505. } else {
  506. /* See if we have a complete record */
  507. rv = ssl2_GatherRecord(ss, 0);
  508. }
  509. if (rv <= 0) {
  510. if (rv == 0) {
  511. /* EOF */
  512. SSL_TRC(10, ("%d: SSL[%d]: ssl_recv EOF",
  513. SSL_GETPID(), ss->fd));
  514. goto done;
  515. }
  516. if ((rv != SECWouldBlock) &&
  517. (PR_GetError() != PR_WOULD_BLOCK_ERROR)) {
  518. /* Some random error */
  519. goto done;
  520. }
  521. /*
  522. ** Gather record is blocked waiting for more record data to
  523. ** arrive. Try to process what we have already received
  524. */
  525. } else {
  526. /* Gather record has finished getting a complete record */
  527. }
  528. /* See if any clear data is now available */
  529. available = ss->gs.writeOffset - ss->gs.readOffset;
  530. if (available == 0) {
  531. /*
  532. ** No partial data is available. Force error code to
  533. ** EWOULDBLOCK so that caller will try again later. Note
  534. ** that the error code is probably EWOULDBLOCK already,
  535. ** but if it isn't (for example, if we received a zero
  536. ** length record) then this will force it to be correct.
  537. */
  538. PORT_SetError(PR_WOULD_BLOCK_ERROR);
  539. rv = SECFailure;
  540. goto done;
  541. }
  542. SSL_TRC(30, ("%d: SSL[%d]: partial data ready, available=%d",
  543. SSL_GETPID(), ss->fd, available));
  544. }
  545. /* Dole out clear data to reader */
  546. amount = PR_MIN(len, available);
  547. PORT_Memcpy(out, ss->gs.buf.buf + ss->gs.readOffset, amount);
  548. if (!(flags & PR_MSG_PEEK)) {
  549. ss->gs.readOffset += amount;
  550. }
  551. rv = amount;
  552. SSL_TRC(30, ("%d: SSL[%d]: amount=%d available=%d",
  553. SSL_GETPID(), ss->fd, amount, available));
  554. PRINT_BUF(4, (ss, "DoRecv receiving plaintext:", out, amount));
  555. done:
  556. ssl_ReleaseRecvBufLock(ss);
  557. return rv;
  558. }
  559. /************************************************************************/
  560. SSLKEAType
  561. ssl_FindCertKEAType(CERTCertificate * cert)
  562. {
  563. SSLKEAType keaType = kt_null;
  564. int tag;
  565. if (!cert) goto loser;
  566. tag = SECOID_GetAlgorithmTag(&(cert->subjectPublicKeyInfo.algorithm));
  567. switch (tag) {
  568. case SEC_OID_X500_RSA_ENCRYPTION:
  569. case SEC_OID_PKCS1_RSA_ENCRYPTION:
  570. keaType = kt_rsa;
  571. break;
  572. case SEC_OID_X942_DIFFIE_HELMAN_KEY:
  573. keaType = kt_dh;
  574. break;
  575. #ifdef NSS_ENABLE_ECC
  576. case SEC_OID_ANSIX962_EC_PUBLIC_KEY:
  577. keaType = kt_ecdh;
  578. break;
  579. #endif /* NSS_ENABLE_ECC */
  580. default:
  581. keaType = kt_null;
  582. }
  583. loser:
  584. return keaType;
  585. }
  586. static const PRCallOnceType pristineCallOnce;
  587. static PRCallOnceType setupServerCAListOnce;
  588. static SECStatus serverCAListShutdown(void* appData, void* nssData)
  589. {
  590. PORT_Assert(ssl3_server_ca_list);
  591. if (ssl3_server_ca_list) {
  592. CERT_FreeDistNames(ssl3_server_ca_list);
  593. ssl3_server_ca_list = NULL;
  594. }
  595. setupServerCAListOnce = pristineCallOnce;
  596. return SECSuccess;
  597. }
  598. static PRStatus serverCAListSetup(void *arg)
  599. {
  600. CERTCertDBHandle *dbHandle = (CERTCertDBHandle *)arg;
  601. SECStatus rv = NSS_RegisterShutdown(serverCAListShutdown, NULL);
  602. PORT_Assert(SECSuccess == rv);
  603. if (SECSuccess == rv) {
  604. ssl3_server_ca_list = CERT_GetSSLCACerts(dbHandle);
  605. return PR_SUCCESS;
  606. }
  607. return PR_FAILURE;
  608. }
  609. SECStatus
  610. ssl_ConfigSecureServer(sslSocket *ss, CERTCertificate *cert,
  611. const CERTCertificateList *certChain,
  612. ssl3KeyPair *keyPair, SSLKEAType kea)
  613. {
  614. CERTCertificateList *localCertChain = NULL;
  615. sslServerCerts *sc = ss->serverCerts + kea;
  616. /* load the server certificate */
  617. if (sc->serverCert != NULL) {
  618. CERT_DestroyCertificate(sc->serverCert);
  619. sc->serverCert = NULL;
  620. sc->serverKeyBits = 0;
  621. }
  622. /* load the server cert chain */
  623. if (sc->serverCertChain != NULL) {
  624. CERT_DestroyCertificateList(sc->serverCertChain);
  625. sc->serverCertChain = NULL;
  626. }
  627. if (cert) {
  628. sc->serverCert = CERT_DupCertificate(cert);
  629. /* get the size of the cert's public key, and remember it */
  630. sc->serverKeyBits = SECKEY_PublicKeyStrengthInBits(keyPair->pubKey);
  631. if (!certChain) {
  632. localCertChain =
  633. CERT_CertChainFromCert(sc->serverCert, certUsageSSLServer,
  634. PR_TRUE);
  635. if (!localCertChain)
  636. goto loser;
  637. }
  638. sc->serverCertChain = (certChain) ? CERT_DupCertList(certChain) :
  639. localCertChain;
  640. if (!sc->serverCertChain) {
  641. goto loser;
  642. }
  643. localCertChain = NULL; /* consumed */
  644. }
  645. /* get keyPair */
  646. if (sc->serverKeyPair != NULL) {
  647. ssl3_FreeKeyPair(sc->serverKeyPair);
  648. sc->serverKeyPair = NULL;
  649. }
  650. if (keyPair) {
  651. SECKEY_CacheStaticFlags(keyPair->privKey);
  652. sc->serverKeyPair = ssl3_GetKeyPairRef(keyPair);
  653. }
  654. if (kea == kt_rsa && cert && sc->serverKeyBits > 512 &&
  655. !ss->opt.noStepDown && !ss->stepDownKeyPair) {
  656. if (ssl3_CreateRSAStepDownKeys(ss) != SECSuccess) {
  657. goto loser;
  658. }
  659. }
  660. return SECSuccess;
  661. loser:
  662. if (localCertChain) {
  663. CERT_DestroyCertificateList(localCertChain);
  664. }
  665. if (sc->serverCert != NULL) {
  666. CERT_DestroyCertificate(sc->serverCert);
  667. sc->serverCert = NULL;
  668. }
  669. if (sc->serverCertChain != NULL) {
  670. CERT_DestroyCertificateList(sc->serverCertChain);
  671. sc->serverCertChain = NULL;
  672. }
  673. if (sc->serverKeyPair != NULL) {
  674. ssl3_FreeKeyPair(sc->serverKeyPair);
  675. sc->serverKeyPair = NULL;
  676. }
  677. return SECFailure;
  678. }
  679. /* XXX need to protect the data that gets changed here.!! */
  680. SECStatus
  681. SSL_ConfigSecureServer(PRFileDesc *fd, CERTCertificate *cert,
  682. SECKEYPrivateKey *key, SSL3KEAType kea)
  683. {
  684. return SSL_ConfigSecureServerWithCertChain(fd, cert, NULL, key, kea);
  685. }
  686. SECStatus
  687. SSL_ConfigSecureServerWithCertChain(PRFileDesc *fd, CERTCertificate *cert,
  688. const CERTCertificateList *certChainOpt,
  689. SECKEYPrivateKey *key, SSL3KEAType kea)
  690. {
  691. sslSocket *ss;
  692. SECKEYPublicKey *pubKey = NULL;
  693. ssl3KeyPair *keyPair = NULL;
  694. SECStatus rv = SECFailure;
  695. ss = ssl_FindSocket(fd);
  696. if (!ss) {
  697. return SECFailure;
  698. }
  699. /* Both key and cert must have a value or be NULL */
  700. /* Passing a value of NULL will turn off key exchange algorithms that were
  701. * previously turned on */
  702. if (!cert != !key) {
  703. PORT_SetError(SEC_ERROR_INVALID_ARGS);
  704. return SECFailure;
  705. }
  706. /* make sure the key exchange is recognized */
  707. if ((kea >= kt_kea_size) || (kea < kt_null)) {
  708. PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG);
  709. return SECFailure;
  710. }
  711. if (kea != ssl_FindCertKEAType(cert)) {
  712. PORT_SetError(SSL_ERROR_CERT_KEA_MISMATCH);
  713. return SECFailure;
  714. }
  715. if (cert) {
  716. /* get the size of the cert's public key, and remember it */
  717. pubKey = CERT_ExtractPublicKey(cert);
  718. if (!pubKey)
  719. return SECFailure;
  720. }
  721. if (key) {
  722. SECKEYPrivateKey * keyCopy = NULL;
  723. CK_MECHANISM_TYPE keyMech = CKM_INVALID_MECHANISM;
  724. if (key->pkcs11Slot) {
  725. PK11SlotInfo * bestSlot;
  726. bestSlot = PK11_ReferenceSlot(key->pkcs11Slot);
  727. if (bestSlot) {
  728. keyCopy = PK11_CopyTokenPrivKeyToSessionPrivKey(bestSlot, key);
  729. PK11_FreeSlot(bestSlot);
  730. }
  731. }
  732. if (keyCopy == NULL)
  733. keyMech = PK11_MapSignKeyType(key->keyType);
  734. if (keyMech != CKM_INVALID_MECHANISM) {
  735. PK11SlotInfo * bestSlot;
  736. /* XXX Maybe should be bestSlotMultiple? */
  737. bestSlot = PK11_GetBestSlot(keyMech, NULL /* wincx */);
  738. if (bestSlot) {
  739. keyCopy = PK11_CopyTokenPrivKeyToSessionPrivKey(bestSlot, key);
  740. PK11_FreeSlot(bestSlot);
  741. }
  742. }
  743. if (keyCopy == NULL)
  744. keyCopy = SECKEY_CopyPrivateKey(key);
  745. if (keyCopy == NULL)
  746. goto loser;
  747. keyPair = ssl3_NewKeyPair(keyCopy, pubKey);
  748. if (keyPair == NULL) {
  749. SECKEY_DestroyPrivateKey(keyCopy);
  750. goto loser;
  751. }
  752. pubKey = NULL; /* adopted by serverKeyPair */
  753. }
  754. if (ssl_ConfigSecureServer(ss, cert, certChainOpt,
  755. keyPair, kea) == SECFailure) {
  756. goto loser;
  757. }
  758. /* Only do this once because it's global. */
  759. if (PR_SUCCESS == PR_CallOnceWithArg(&setupServerCAListOnce,
  760. &serverCAListSetup,
  761. (void *)(ss->dbHandle))) {
  762. rv = SECSuccess;
  763. }
  764. loser:
  765. if (keyPair) {
  766. ssl3_FreeKeyPair(keyPair);
  767. }
  768. if (pubKey) {
  769. SECKEY_DestroyPublicKey(pubKey);
  770. pubKey = NULL;
  771. }
  772. return rv;
  773. }
  774. /************************************************************************/
  775. SECStatus
  776. ssl_CreateSecurityInfo(sslSocket *ss)
  777. {
  778. SECStatus status;
  779. /* initialize sslv2 socket to send data in the clear. */
  780. ssl2_UseClearSendFunc(ss);
  781. ss->sec.blockSize = 1;
  782. ss->sec.blockShift = 0;
  783. ssl_GetXmitBufLock(ss);
  784. status = sslBuffer_Grow(&ss->sec.writeBuf, 4096);
  785. ssl_ReleaseXmitBufLock(ss);
  786. return status;
  787. }
  788. SECStatus
  789. ssl_CopySecurityInfo(sslSocket *ss, sslSocket *os)
  790. {
  791. ss->sec.send = os->sec.send;
  792. ss->sec.isServer = os->sec.isServer;
  793. ss->sec.keyBits = os->sec.keyBits;
  794. ss->sec.secretKeyBits = os->sec.secretKeyBits;
  795. ss->sec.peerCert = CERT_DupCertificate(os->sec.peerCert);
  796. if (os->sec.peerCert && !ss->sec.peerCert)
  797. goto loser;
  798. ss->sec.cache = os->sec.cache;
  799. ss->sec.uncache = os->sec.uncache;
  800. /* we don't dup the connection info. */
  801. ss->sec.sendSequence = os->sec.sendSequence;
  802. ss->sec.rcvSequence = os->sec.rcvSequence;
  803. if (os->sec.hash && os->sec.hashcx) {
  804. ss->sec.hash = os->sec.hash;
  805. ss->sec.hashcx = os->sec.hash->clone(os->sec.hashcx);
  806. if (os->sec.hashcx && !ss->sec.hashcx)
  807. goto loser;
  808. } else {
  809. ss->sec.hash = NULL;
  810. ss->sec.hashcx = NULL;
  811. }
  812. SECITEM_CopyItem(0, &ss->sec.sendSecret, &os->sec.sendSecret);
  813. if (os->sec.sendSecret.data && !ss->sec.sendSecret.data)
  814. goto loser;
  815. SECITEM_CopyItem(0, &ss->sec.rcvSecret, &os->sec.rcvSecret);
  816. if (os->sec.rcvSecret.data && !ss->sec.rcvSecret.data)
  817. goto loser;
  818. /* XXX following code is wrong if either cx != 0 */
  819. PORT_Assert(os->sec.readcx == 0);
  820. PORT_Assert(os->sec.writecx == 0);
  821. ss->sec.readcx = os->sec.readcx;
  822. ss->sec.writecx = os->sec.writecx;
  823. ss->sec.destroy = 0;
  824. ss->sec.enc = os->sec.enc;
  825. ss->sec.dec = os->sec.dec;
  826. ss->sec.blockShift = os->sec.blockShift;
  827. ss->sec.blockSize = os->sec.blockSize;
  828. return SECSuccess;
  829. loser:
  830. return SECFailure;
  831. }
  832. /* Reset sec back to its initial state.
  833. ** Caller holds any relevant locks.
  834. */
  835. void
  836. ssl_ResetSecurityInfo(sslSecurityInfo *sec, PRBool doMemset)
  837. {
  838. /* Destroy MAC */
  839. if (sec->hash && sec->hashcx) {
  840. (*sec->hash->destroy)(sec->hashcx, PR_TRUE);
  841. sec->hashcx = NULL;
  842. sec->hash = NULL;
  843. }
  844. SECITEM_ZfreeItem(&sec->sendSecret, PR_FALSE);
  845. SECITEM_ZfreeItem(&sec->rcvSecret, PR_FALSE);
  846. /* Destroy ciphers */
  847. if (sec->destroy) {
  848. (*sec->destroy)(sec->readcx, PR_TRUE);
  849. (*sec->destroy)(sec->writecx, PR_TRUE);
  850. sec->readcx = NULL;
  851. sec->writecx = NULL;
  852. } else {
  853. PORT_Assert(sec->readcx == 0);
  854. PORT_Assert(sec->writecx == 0);
  855. }
  856. sec->readcx = 0;
  857. sec->writecx = 0;
  858. if (sec->localCert) {
  859. CERT_DestroyCertificate(sec->localCert);
  860. sec->localCert = NULL;
  861. }
  862. if (sec->peerCert) {
  863. CERT_DestroyCertificate(sec->peerCert);
  864. sec->peerCert = NULL;
  865. }
  866. if (sec->peerKey) {
  867. SECKEY_DestroyPublicKey(sec->peerKey);
  868. sec->peerKey = NULL;
  869. }
  870. /* cleanup the ci */
  871. if (sec->ci.sid != NULL) {
  872. ssl_FreeSID(sec->ci.sid);
  873. }
  874. PORT_ZFree(sec->ci.sendBuf.buf, sec->ci.sendBuf.space);
  875. if (doMemset) {
  876. memset(&sec->ci, 0, sizeof sec->ci);
  877. }
  878. }
  879. /*
  880. ** Called from SSL_ResetHandshake (above), and
  881. ** from ssl_FreeSocket in sslsock.c
  882. ** Caller should hold relevant locks (e.g. XmitBufLock)
  883. */
  884. void
  885. ssl_DestroySecurityInfo(sslSecurityInfo *sec)
  886. {
  887. ssl_ResetSecurityInfo(sec, PR_FALSE);
  888. PORT_ZFree(sec->writeBuf.buf, sec->writeBuf.space);
  889. sec->writeBuf.buf = 0;
  890. memset(sec, 0, sizeof *sec);
  891. }
  892. /************************************************************************/
  893. int
  894. ssl_SecureConnect(sslSocket *ss, const PRNetAddr *sa)
  895. {
  896. PRFileDesc *osfd = ss->fd->lower;
  897. int rv;
  898. if ( ss->opt.handshakeAsServer ) {
  899. ss->securityHandshake = ssl2_BeginServerHandshake;
  900. ss->handshaking = sslHandshakingAsServer;
  901. } else {
  902. ss->securityHandshake = ssl2_BeginClientHandshake;
  903. ss->handshaking = sslHandshakingAsClient;
  904. }
  905. /* connect to server */
  906. rv = osfd->methods->connect(osfd, sa, ss->cTimeout);
  907. if (rv == PR_SUCCESS) {
  908. ss->TCPconnected = 1;
  909. } else {
  910. int err = PR_GetError();
  911. SSL_DBG(("%d: SSL[%d]: connect failed, errno=%d",
  912. SSL_GETPID(), ss->fd, err));
  913. if (err == PR_IS_CONNECTED_ERROR) {
  914. ss->TCPconnected = 1;
  915. }
  916. }
  917. SSL_TRC(5, ("%d: SSL[%d]: secure connect completed, rv == %d",
  918. SSL_GETPID(), ss->fd, rv));
  919. return rv;
  920. }
  921. /*
  922. * The TLS 1.2 RFC 5246, Section 7.2.1 says:
  923. *
  924. * Unless some other fatal alert has been transmitted, each party is
  925. * required to send a close_notify alert before closing the write side
  926. * of the connection. The other party MUST respond with a close_notify
  927. * alert of its own and close down the connection immediately,
  928. * discarding any pending writes. It is not required for the initiator
  929. * of the close to wait for the responding close_notify alert before
  930. * closing the read side of the connection.
  931. *
  932. * The second sentence requires that we send a close_notify alert when we
  933. * have received a close_notify alert. In practice, all SSL implementations
  934. * close the socket immediately after sending a close_notify alert (which is
  935. * allowed by the third sentence), so responding with a close_notify alert
  936. * would result in a write failure with the ECONNRESET error. This is why
  937. * we don't respond with a close_notify alert.
  938. *
  939. * Also, in the unlikely event that the TCP pipe is full and the peer stops
  940. * reading, the SSL3_SendAlert call in ssl_SecureClose and ssl_SecureShutdown
  941. * may block indefinitely in blocking mode, and may fail (without retrying)
  942. * in non-blocking mode.
  943. */
  944. int
  945. ssl_SecureClose(sslSocket *ss)
  946. {
  947. int rv;
  948. if (ss->version >= SSL_LIBRARY_VERSION_3_0 &&
  949. !(ss->shutdownHow & ssl_SHUTDOWN_SEND) &&
  950. ss->firstHsDone &&
  951. !ss->recvdCloseNotify &&
  952. ss->ssl3.initialized) {
  953. /* We don't want the final alert to be Nagle delayed. */
  954. if (!ss->delayDisabled) {
  955. ssl_EnableNagleDelay(ss, PR_FALSE);
  956. ss->delayDisabled = 1;
  957. }
  958. (void) SSL3_SendAlert(ss, alert_warning, close_notify);
  959. }
  960. rv = ssl_DefClose(ss);
  961. return rv;
  962. }
  963. /* Caller handles all locking */
  964. int
  965. ssl_SecureShutdown(sslSocket *ss, int nsprHow)
  966. {
  967. PRFileDesc *osfd = ss->fd->lower;
  968. int rv;
  969. PRIntn sslHow = nsprHow + 1;
  970. if ((unsigned)nsprHow > PR_SHUTDOWN_BOTH) {
  971. PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
  972. return PR_FAILURE;
  973. }
  974. if ((sslHow & ssl_SHUTDOWN_SEND) != 0 &&
  975. ss->version >= SSL_LIBRARY_VERSION_3_0 &&
  976. !(ss->shutdownHow & ssl_SHUTDOWN_SEND) &&
  977. ss->firstHsDone &&
  978. !ss->recvdCloseNotify &&
  979. ss->ssl3.initialized) {
  980. (void) SSL3_SendAlert(ss, alert_warning, close_notify);
  981. }
  982. rv = osfd->methods->shutdown(osfd, nsprHow);
  983. ss->shutdownHow |= sslHow;
  984. return rv;
  985. }
  986. /************************************************************************/
  987. int
  988. ssl_SecureRecv(sslSocket *ss, unsigned char *buf, int len, int flags)
  989. {
  990. sslSecurityInfo *sec;
  991. int rv = 0;
  992. sec = &ss->sec;
  993. if (ss->shutdownHow & ssl_SHUTDOWN_RCV) {
  994. PORT_SetError(PR_SOCKET_SHUTDOWN_ERROR);
  995. return PR_FAILURE;
  996. }
  997. if (flags & ~PR_MSG_PEEK) {
  998. PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
  999. return PR_FAILURE;
  1000. }
  1001. if (!ssl_SocketIsBlocking(ss) && !ss->opt.fdx) {
  1002. ssl_GetXmitBufLock(ss);
  1003. if (ss->pendingBuf.len != 0) {
  1004. rv = ssl_SendSavedWriteData(ss);
  1005. if ((rv < 0) && (PORT_GetError() != PR_WOULD_BLOCK_ERROR)) {
  1006. ssl_ReleaseXmitBufLock(ss);
  1007. return SECFailure;
  1008. }
  1009. }
  1010. ssl_ReleaseXmitBufLock(ss);
  1011. }
  1012. rv = 0;
  1013. /* If any of these is non-zero, the initial handshake is not done. */
  1014. if (!ss->firstHsDone) {
  1015. ssl_Get1stHandshakeLock(ss);
  1016. if (ss->handshake || ss->nextHandshake || ss->securityHandshake) {
  1017. rv = ssl_Do1stHandshake(ss);
  1018. }
  1019. ssl_Release1stHandshakeLock(ss);
  1020. }
  1021. if (rv < 0) {
  1022. return rv;
  1023. }
  1024. if (len == 0) return 0;
  1025. rv = DoRecv(ss, (unsigned char*) buf, len, flags);
  1026. SSL_TRC(2, ("%d: SSL[%d]: recving %d bytes securely (errno=%d)",
  1027. SSL_GETPID(), ss->fd, rv, PORT_GetError()));
  1028. return rv;
  1029. }
  1030. int
  1031. ssl_SecureRead(sslSocket *ss, unsigned char *buf, int len)
  1032. {
  1033. return ssl_SecureRecv(ss, buf, len, 0);
  1034. }
  1035. /* Caller holds the SSL Socket's write lock. SSL_LOCK_WRITER(ss) */
  1036. int
  1037. ssl_SecureSend(sslSocket *ss, const unsigned char *buf, int len, int flags)
  1038. {
  1039. int rv = 0;
  1040. SSL_TRC(2, ("%d: SSL[%d]: SecureSend: sending %d bytes",
  1041. SSL_GETPID(), ss->fd, len));
  1042. if (ss->shutdownHow & ssl_SHUTDOWN_SEND) {
  1043. PORT_SetError(PR_SOCKET_SHUTDOWN_ERROR);
  1044. rv = PR_FAILURE;
  1045. goto done;
  1046. }
  1047. if (flags) {
  1048. PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
  1049. rv = PR_FAILURE;
  1050. goto done;
  1051. }
  1052. ssl_GetXmitBufLock(ss);
  1053. if (ss->pendingBuf.len != 0) {
  1054. PORT_Assert(ss->pendingBuf.len > 0);
  1055. rv = ssl_SendSavedWriteData(ss);
  1056. if (rv >= 0 && ss->pendingBuf.len != 0) {
  1057. PORT_Assert(ss->pendingBuf.len > 0);
  1058. PORT_SetError(PR_WOULD_BLOCK_ERROR);
  1059. rv = SECFailure;
  1060. }
  1061. }
  1062. ssl_ReleaseXmitBufLock(ss);
  1063. if (rv < 0) {
  1064. goto done;
  1065. }
  1066. if (len > 0)
  1067. ss->writerThread = PR_GetCurrentThread();
  1068. /* If any of these is non-zero, the initial handshake is not done. */
  1069. if (!ss->firstHsDone) {
  1070. PRBool canFalseStart = PR_FALSE;
  1071. ssl_Get1stHandshakeLock(ss);
  1072. if (ss->version >= SSL_LIBRARY_VERSION_3_0) {
  1073. ssl_GetSSL3HandshakeLock(ss);
  1074. if ((ss->ssl3.hs.ws == wait_change_cipher ||
  1075. ss->ssl3.hs.ws == wait_finished ||
  1076. ss->ssl3.hs.ws == wait_new_session_ticket) &&
  1077. ssl3_CanFalseStart(ss)) {
  1078. canFalseStart = PR_TRUE;
  1079. }
  1080. ssl_ReleaseSSL3HandshakeLock(ss);
  1081. }
  1082. if (!canFalseStart &&
  1083. (ss->handshake || ss->nextHandshake || ss->securityHandshake)) {
  1084. rv = ssl_Do1stHandshake(ss);
  1085. }
  1086. ssl_Release1stHandshakeLock(ss);
  1087. }
  1088. if (rv < 0) {
  1089. ss->writerThread = NULL;
  1090. goto done;
  1091. }
  1092. /* Check for zero length writes after we do housekeeping so we make forward
  1093. * progress.
  1094. */
  1095. if (len == 0) {
  1096. rv = 0;
  1097. goto done;
  1098. }
  1099. PORT_Assert(buf != NULL);
  1100. if (!buf) {
  1101. PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
  1102. rv = PR_FAILURE;
  1103. goto done;
  1104. }
  1105. /* Send out the data using one of these functions:
  1106. * ssl2_SendClear, ssl2_SendStream, ssl2_SendBlock,
  1107. * ssl3_SendApplicationData
  1108. */
  1109. ssl_GetXmitBufLock(ss);
  1110. rv = (*ss->sec.send)(ss, buf, len, flags);
  1111. ssl_ReleaseXmitBufLock(ss);
  1112. ss->writerThread = NULL;
  1113. done:
  1114. if (rv < 0) {
  1115. SSL_TRC(2, ("%d: SSL[%d]: SecureSend: returning %d count, error %d",
  1116. SSL_GETPID(), ss->fd, rv, PORT_GetError()));
  1117. } else {
  1118. SSL_TRC(2, ("%d: SSL[%d]: SecureSend: returning %d count",
  1119. SSL_GETPID(), ss->fd, rv));
  1120. }
  1121. return rv;
  1122. }
  1123. int
  1124. ssl_SecureWrite(sslSocket *ss, const unsigned char *buf, int len)
  1125. {
  1126. return ssl_SecureSend(ss, buf, len, 0);
  1127. }
  1128. SECStatus
  1129. SSL_BadCertHook(PRFileDesc *fd, SSLBadCertHandler f, void *arg)
  1130. {
  1131. sslSocket *ss;
  1132. ss = ssl_FindSocket(fd);
  1133. if (!ss) {
  1134. SSL_DBG(("%d: SSL[%d]: bad socket in SSLBadCertHook",
  1135. SSL_GETPID(), fd));
  1136. return SECFailure;
  1137. }
  1138. ss->handleBadCert = f;
  1139. ss->badCertArg = arg;
  1140. return SECSuccess;
  1141. }
  1142. /*
  1143. * Allow the application to pass the url or hostname into the SSL library
  1144. * so that we can do some checking on it. It will be used for the value in
  1145. * SNI extension of client hello message.
  1146. */
  1147. SECStatus
  1148. SSL_SetURL(PRFileDesc *fd, const char *url)
  1149. {
  1150. sslSocket * ss = ssl_FindSocket(fd);
  1151. SECStatus rv = SECSuccess;
  1152. if (!ss) {
  1153. SSL_DBG(("%d: SSL[%d]: bad socket in SSLSetURL",
  1154. SSL_GETPID(), fd));
  1155. return SECFailure;
  1156. }
  1157. ssl_Get1stHandshakeLock(ss);
  1158. ssl_GetSSL3HandshakeLock(ss);
  1159. if ( ss->url ) {
  1160. PORT_Free((void *)ss->url); /* CONST */
  1161. }
  1162. ss->url = (const char *)PORT_Strdup(url);
  1163. if ( ss->url == NULL ) {
  1164. rv = SECFailure;
  1165. }
  1166. ssl_ReleaseSSL3HandshakeLock(ss);
  1167. ssl_Release1stHandshakeLock(ss);
  1168. return rv;
  1169. }
  1170. /*
  1171. * Allow the application to pass the set of trust anchors
  1172. */
  1173. SECStatus
  1174. SSL_SetTrustAnchors(PRFileDesc *fd, CERTCertList *certList)
  1175. {
  1176. sslSocket * ss = ssl_FindSocket(fd);
  1177. CERTDistNames *names = NULL;
  1178. if (!certList) {
  1179. PORT_SetError(SEC_ERROR_INVALID_ARGS);
  1180. return SECFailure;
  1181. }
  1182. if (!ss) {
  1183. SSL_DBG(("%d: SSL[%d]: bad socket in SSL_SetTrustAnchors",
  1184. SSL_GETPID(), fd));
  1185. return SECFailure;
  1186. }
  1187. names = CERT_DistNamesFromCertList(certList);
  1188. if (names == NULL) {
  1189. return SECFailure;
  1190. }
  1191. ssl_Get1stHandshakeLock(ss);
  1192. ssl_GetSSL3HandshakeLock(ss);
  1193. if (ss->ssl3.ca_list) {
  1194. CERT_FreeDistNames(ss->ssl3.ca_list);
  1195. }
  1196. ss->ssl3.ca_list = names;
  1197. ssl_ReleaseSSL3HandshakeLock(ss);
  1198. ssl_Release1stHandshakeLock(ss);
  1199. return SECSuccess;
  1200. }
  1201. /*
  1202. ** Returns Negative number on error, zero or greater on success.
  1203. ** Returns the amount of data immediately available to be read.
  1204. */
  1205. int
  1206. SSL_DataPending(PRFileDesc *fd)
  1207. {
  1208. sslSocket *ss;
  1209. int rv = 0;
  1210. ss = ssl_FindSocket(fd);
  1211. if (ss && ss->opt.useSecurity) {
  1212. ssl_GetRecvBufLock(ss);
  1213. rv = ss->gs.writeOffset - ss->gs.readOffset;
  1214. ssl_ReleaseRecvBufLock(ss);
  1215. }
  1216. return rv;
  1217. }
  1218. SECStatus
  1219. SSL_InvalidateSession(PRFileDesc *fd)
  1220. {
  1221. sslSocket * ss = ssl_FindSocket(fd);
  1222. SECStatus rv = SECFailure;
  1223. if (ss) {
  1224. ssl_Get1stHandshakeLock(ss);
  1225. ssl_GetSSL3HandshakeLock(ss);
  1226. if (ss->sec.ci.sid) {
  1227. ss->sec.uncache(ss->sec.ci.sid);
  1228. rv = SECSuccess;
  1229. }
  1230. ssl_ReleaseSSL3HandshakeLock(ss);
  1231. ssl_Release1stHandshakeLock(ss);
  1232. }
  1233. return rv;
  1234. }
  1235. SECItem *
  1236. SSL_GetSessionID(PRFileDesc *fd)
  1237. {
  1238. sslSocket * ss;
  1239. SECItem * item = NULL;
  1240. ss = ssl_FindSocket(fd);
  1241. if (ss) {
  1242. ssl_Get1stHandshakeLock(ss);
  1243. ssl_GetSSL3HandshakeLock(ss);
  1244. if (ss->opt.useSecurity && ss->firstHsDone && ss->sec.ci.sid) {
  1245. item = (SECItem *)PORT_Alloc(sizeof(SECItem));
  1246. if (item) {
  1247. sslSessionID * sid = ss->sec.ci.sid;
  1248. if (sid->version < SSL_LIBRARY_VERSION_3_0) {
  1249. item->len = SSL2_SESSIONID_BYTES;
  1250. item->data = (unsigned char*)PORT_Alloc(item->len);
  1251. PORT_Memcpy(item->data, sid->u.ssl2.sessionID, item->len);
  1252. } else {
  1253. item->len = sid->u.ssl3.sessionIDLength;
  1254. item->data = (unsigned char*)PORT_Alloc(item->len);
  1255. PORT_Memcpy(item->data, sid->u.ssl3.sessionID, item->len);
  1256. }
  1257. }
  1258. }
  1259. ssl_ReleaseSSL3HandshakeLock(ss);
  1260. ssl_Release1stHandshakeLock(ss);
  1261. }
  1262. return item;
  1263. }
  1264. SECStatus
  1265. SSL_CertDBHandleSet(PRFileDesc *fd, CERTCertDBHandle *dbHandle)
  1266. {
  1267. sslSocket * ss;
  1268. ss = ssl_FindSocket(fd);
  1269. if (!ss)
  1270. return SECFailure;
  1271. if (!dbHandle) {
  1272. PORT_SetError(SEC_ERROR_INVALID_ARGS);
  1273. return SECFailure;
  1274. }
  1275. ss->dbHandle = dbHandle;
  1276. return SECSuccess;
  1277. }
  1278. /* DO NOT USE. This function was exported in ssl.def with the wrong signature;
  1279. * this implementation exists to maintain link-time compatibility.
  1280. */
  1281. int
  1282. SSL_RestartHandshakeAfterCertReq(sslSocket * ss,
  1283. CERTCertificate * cert,
  1284. SECKEYPrivateKey * key,
  1285. CERTCertificateList *certChain)
  1286. {
  1287. PORT_SetError(PR_NOT_IMPLEMENTED_ERROR);
  1288. return -1;
  1289. }
  1290. /* DO NOT USE. This function was exported in ssl.def with the wrong signature;
  1291. * this implementation exists to maintain link-time compatibility.
  1292. */
  1293. int
  1294. SSL_RestartHandshakeAfterServerCert(sslSocket * ss)
  1295. {
  1296. PORT_SetError(PR_NOT_IMPLEMENTED_ERROR);
  1297. return -1;
  1298. }
  1299. /* See documentation in ssl.h */
  1300. SECStatus
  1301. SSL_AuthCertificateComplete(PRFileDesc *fd, PRErrorCode status)
  1302. {
  1303. SECStatus rv;
  1304. sslSocket *ss = ssl_FindSocket(fd);
  1305. if (!ss) {
  1306. SSL_DBG(("%d: SSL[%d]: bad socket in SSL_AuthCertificateComplete",
  1307. SSL_GETPID(), fd));
  1308. return SECFailure;
  1309. }
  1310. ssl_Get1stHandshakeLock(ss);
  1311. if (!ss->ssl3.initialized) {
  1312. PORT_SetError(SEC_ERROR_INVALID_ARGS);
  1313. rv = SECFailure;
  1314. } else if (ss->version < SSL_LIBRARY_VERSION_3_0) {
  1315. PORT_SetError(SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_SSL2);
  1316. rv = SECFailure;
  1317. } else {
  1318. rv = ssl3_AuthCertificateComplete(ss, status);
  1319. }
  1320. ssl_Release1stHandshakeLock(ss);
  1321. return rv;
  1322. }
  1323. /* For more info see ssl.h */
  1324. SECStatus
  1325. SSL_SNISocketConfigHook(PRFileDesc *fd, SSLSNISocketConfig func,
  1326. void *arg)
  1327. {
  1328. sslSocket *ss;
  1329. ss = ssl_FindSocket(fd);
  1330. if (!ss) {
  1331. SSL_DBG(("%d: SSL[%d]: bad socket in SNISocketConfigHook",
  1332. SSL_GETPID(), fd));
  1333. return SECFailure;
  1334. }
  1335. ss->sniSocketConfig = func;
  1336. ss->sniSocketConfigArg = arg;
  1337. return SECSuccess;
  1338. }