25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

1217 lines
39 KiB

  1. /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
  2. * All rights reserved.
  3. *
  4. * This package is an SSL implementation written
  5. * by Eric Young (eay@cryptsoft.com).
  6. * The implementation was written so as to conform with Netscapes SSL.
  7. *
  8. * This library is free for commercial and non-commercial use as long as
  9. * the following conditions are aheared to. The following conditions
  10. * apply to all code found in this distribution, be it the RC4, RSA,
  11. * lhash, DES, etc., code; not just the SSL code. The SSL documentation
  12. * included with this distribution is covered by the same copyright terms
  13. * except that the holder is Tim Hudson (tjh@cryptsoft.com).
  14. *
  15. * Copyright remains Eric Young's, and as such any Copyright notices in
  16. * the code are not to be removed.
  17. * If this package is used in a product, Eric Young should be given attribution
  18. * as the author of the parts of the library used.
  19. * This can be in the form of a textual message at program startup or
  20. * in documentation (online or textual) provided with the package.
  21. *
  22. * Redistribution and use in source and binary forms, with or without
  23. * modification, are permitted provided that the following conditions
  24. * are met:
  25. * 1. Redistributions of source code must retain the copyright
  26. * notice, this list of conditions and the following disclaimer.
  27. * 2. Redistributions in binary form must reproduce the above copyright
  28. * notice, this list of conditions and the following disclaimer in the
  29. * documentation and/or other materials provided with the distribution.
  30. * 3. All advertising materials mentioning features or use of this software
  31. * must display the following acknowledgement:
  32. * "This product includes cryptographic software written by
  33. * Eric Young (eay@cryptsoft.com)"
  34. * The word 'cryptographic' can be left out if the rouines from the library
  35. * being used are not cryptographic related :-).
  36. * 4. If you include any Windows specific code (or a derivative thereof) from
  37. * the apps directory (application code) you must include an acknowledgement:
  38. * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
  39. *
  40. * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
  41. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  42. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  43. * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
  44. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  45. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  46. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  47. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  48. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  49. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  50. * SUCH DAMAGE.
  51. *
  52. * The licence and distribution terms for any publically available version or
  53. * derivative of this code cannot be changed. i.e. this code cannot simply be
  54. * copied and put under another distribution licence
  55. * [including the GNU Public Licence.]
  56. */
  57. /* ====================================================================
  58. * Copyright (c) 1998-2002 The OpenSSL Project. All rights reserved.
  59. *
  60. * Redistribution and use in source and binary forms, with or without
  61. * modification, are permitted provided that the following conditions
  62. * are met:
  63. *
  64. * 1. Redistributions of source code must retain the above copyright
  65. * notice, this list of conditions and the following disclaimer.
  66. *
  67. * 2. Redistributions in binary form must reproduce the above copyright
  68. * notice, this list of conditions and the following disclaimer in
  69. * the documentation and/or other materials provided with the
  70. * distribution.
  71. *
  72. * 3. All advertising materials mentioning features or use of this
  73. * software must display the following acknowledgment:
  74. * "This product includes software developed by the OpenSSL Project
  75. * for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
  76. *
  77. * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
  78. * endorse or promote products derived from this software without
  79. * prior written permission. For written permission, please contact
  80. * openssl-core@openssl.org.
  81. *
  82. * 5. Products derived from this software may not be called "OpenSSL"
  83. * nor may "OpenSSL" appear in their names without prior written
  84. * permission of the OpenSSL Project.
  85. *
  86. * 6. Redistributions of any form whatsoever must retain the following
  87. * acknowledgment:
  88. * "This product includes software developed by the OpenSSL Project
  89. * for use in the OpenSSL Toolkit (http://www.openssl.org/)"
  90. *
  91. * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
  92. * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  93. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  94. * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
  95. * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  96. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  97. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  98. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  99. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  100. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  101. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
  102. * OF THE POSSIBILITY OF SUCH DAMAGE.
  103. * ====================================================================
  104. *
  105. * This product includes cryptographic software written by Eric Young
  106. * (eay@cryptsoft.com). This product includes software written by Tim
  107. * Hudson (tjh@cryptsoft.com). */
  108. #include <assert.h>
  109. #include <errno.h>
  110. #include <limits.h>
  111. #include <stdio.h>
  112. #include <openssl/buf.h>
  113. #include <openssl/err.h>
  114. #include <openssl/evp.h>
  115. #include <openssl/mem.h>
  116. #include <openssl/rand.h>
  117. #include "ssl_locl.h"
  118. static int do_ssl3_write(SSL *s, int type, const uint8_t *buf, unsigned int len,
  119. char fragment, char is_fragment);
  120. static int ssl3_get_record(SSL *s);
  121. int ssl3_read_n(SSL *s, int n, int max, int extend) {
  122. /* If |extend| is 0, obtain new n-byte packet;
  123. * if |extend| is 1, increase packet by another n bytes.
  124. *
  125. * The packet will be in the sub-array of |s->s3->rbuf.buf| specified by
  126. * |s->packet| and |s->packet_length|. (If |s->read_ahead| is set, |max|
  127. * bytes may be stored in |rbuf| (plus |s->packet_length| bytes if |extend|
  128. * is one.) */
  129. int i, len, left;
  130. long align = 0;
  131. uint8_t *pkt;
  132. SSL3_BUFFER *rb;
  133. if (n <= 0) {
  134. return n;
  135. }
  136. rb = &s->s3->rbuf;
  137. if (rb->buf == NULL && !ssl3_setup_read_buffer(s)) {
  138. return -1;
  139. }
  140. left = rb->left;
  141. align = (long)rb->buf + SSL3_RT_HEADER_LENGTH;
  142. align = (-align) & (SSL3_ALIGN_PAYLOAD - 1);
  143. if (!extend) {
  144. /* start with empty packet ... */
  145. if (left == 0) {
  146. rb->offset = align;
  147. } else if (align != 0 && left >= SSL3_RT_HEADER_LENGTH) {
  148. /* check if next packet length is large enough to justify payload
  149. * alignment... */
  150. pkt = rb->buf + rb->offset;
  151. if (pkt[0] == SSL3_RT_APPLICATION_DATA && (pkt[3] << 8 | pkt[4]) >= 128) {
  152. /* Note that even if packet is corrupted and its length field is
  153. * insane, we can only be led to wrong decision about whether memmove
  154. * will occur or not. Header values has no effect on memmove arguments
  155. * and therefore no buffer overrun can be triggered. */
  156. memmove(rb->buf + align, pkt, left);
  157. rb->offset = align;
  158. }
  159. }
  160. s->packet = rb->buf + rb->offset;
  161. s->packet_length = 0;
  162. /* ... now we can act as if 'extend' was set */
  163. }
  164. /* For DTLS/UDP reads should not span multiple packets because the read
  165. * operation returns the whole packet at once (as long as it fits into the
  166. * buffer). */
  167. if (SSL_IS_DTLS(s) && left > 0 && n > left) {
  168. n = left;
  169. }
  170. /* if there is enough in the buffer from a previous read, take some */
  171. if (left >= n) {
  172. s->packet_length += n;
  173. rb->left = left - n;
  174. rb->offset += n;
  175. return n;
  176. }
  177. /* else we need to read more data */
  178. len = s->packet_length;
  179. pkt = rb->buf + align;
  180. /* Move any available bytes to front of buffer: |len| bytes already pointed
  181. * to by |packet|, |left| extra ones at the end. */
  182. if (s->packet != pkt) {
  183. /* len > 0 */
  184. memmove(pkt, s->packet, len + left);
  185. s->packet = pkt;
  186. rb->offset = len + align;
  187. }
  188. assert(n <= (int)(rb->len - rb->offset));
  189. if (!s->read_ahead) {
  190. /* ignore max parameter */
  191. max = n;
  192. } else {
  193. if (max < n) {
  194. max = n;
  195. }
  196. if (max > (int)(rb->len - rb->offset)) {
  197. max = rb->len - rb->offset;
  198. }
  199. }
  200. while (left < n) {
  201. /* Now we have len+left bytes at the front of s->s3->rbuf.buf and need to
  202. * read in more until we have len+n (up to len+max if possible). */
  203. ERR_clear_system_error();
  204. if (s->rbio != NULL) {
  205. s->rwstate = SSL_READING;
  206. i = BIO_read(s->rbio, pkt + len + left, max - left);
  207. } else {
  208. OPENSSL_PUT_ERROR(SSL, ssl3_read_n, SSL_R_READ_BIO_NOT_SET);
  209. i = -1;
  210. }
  211. if (i <= 0) {
  212. rb->left = left;
  213. if (s->mode & SSL_MODE_RELEASE_BUFFERS && !SSL_IS_DTLS(s) &&
  214. len + left == 0) {
  215. ssl3_release_read_buffer(s);
  216. }
  217. return i;
  218. }
  219. left += i;
  220. /* reads should *never* span multiple packets for DTLS because the
  221. * underlying transport protocol is message oriented as opposed to byte
  222. * oriented as in the TLS case. */
  223. if (SSL_IS_DTLS(s) && n > left) {
  224. n = left; /* makes the while condition false */
  225. }
  226. }
  227. /* done reading, now the book-keeping */
  228. rb->offset += n;
  229. rb->left = left - n;
  230. s->packet_length += n;
  231. s->rwstate = SSL_NOTHING;
  232. return n;
  233. }
  234. /* MAX_EMPTY_RECORDS defines the number of consecutive, empty records that will
  235. * be processed per call to ssl3_get_record. Without this limit an attacker
  236. * could send empty records at a faster rate than we can process and cause
  237. * ssl3_get_record to loop forever. */
  238. #define MAX_EMPTY_RECORDS 32
  239. /* Call this to get a new input record. It will return <= 0 if more data is
  240. * needed, normally due to an error or non-blocking IO. When it finishes, one
  241. * packet has been decoded and can be found in
  242. * ssl->s3->rrec.type - is the type of record
  243. * ssl->s3->rrec.data - data
  244. * ssl->s3->rrec.length - number of bytes */
  245. /* used only by ssl3_read_bytes */
  246. static int ssl3_get_record(SSL *s) {
  247. int ssl_major, ssl_minor, al;
  248. int n, i, ret = -1;
  249. SSL3_RECORD *rr;
  250. uint8_t *p;
  251. short version;
  252. size_t extra;
  253. unsigned empty_record_count = 0;
  254. rr = &s->s3->rrec;
  255. if (s->options & SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER) {
  256. extra = SSL3_RT_MAX_EXTRA;
  257. } else {
  258. extra = 0;
  259. }
  260. if (extra && !s->s3->init_extra) {
  261. /* An application error: SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER set after
  262. * ssl3_setup_buffers() was done */
  263. OPENSSL_PUT_ERROR(SSL, ssl3_get_record, ERR_R_INTERNAL_ERROR);
  264. return -1;
  265. }
  266. again:
  267. /* check if we have the header */
  268. if (s->rstate != SSL_ST_READ_BODY ||
  269. s->packet_length < SSL3_RT_HEADER_LENGTH) {
  270. n = ssl3_read_n(s, SSL3_RT_HEADER_LENGTH, s->s3->rbuf.len, 0);
  271. if (n <= 0) {
  272. return n; /* error or non-blocking */
  273. }
  274. s->rstate = SSL_ST_READ_BODY;
  275. p = s->packet;
  276. if (s->msg_callback) {
  277. s->msg_callback(0, 0, SSL3_RT_HEADER, p, 5, s, s->msg_callback_arg);
  278. }
  279. /* Pull apart the header into the SSL3_RECORD */
  280. rr->type = *(p++);
  281. ssl_major = *(p++);
  282. ssl_minor = *(p++);
  283. version = (ssl_major << 8) | ssl_minor;
  284. n2s(p, rr->length);
  285. if (s->s3->have_version && version != s->version) {
  286. OPENSSL_PUT_ERROR(SSL, ssl3_get_record, SSL_R_WRONG_VERSION_NUMBER);
  287. if ((s->version & 0xFF00) == (version & 0xFF00)) {
  288. /* Send back error using their minor version number. */
  289. s->version = (unsigned short)version;
  290. }
  291. al = SSL_AD_PROTOCOL_VERSION;
  292. goto f_err;
  293. }
  294. if ((version >> 8) != SSL3_VERSION_MAJOR) {
  295. OPENSSL_PUT_ERROR(SSL, ssl3_get_record, SSL_R_WRONG_VERSION_NUMBER);
  296. goto err;
  297. }
  298. if (rr->length > s->s3->rbuf.len - SSL3_RT_HEADER_LENGTH) {
  299. al = SSL_AD_RECORD_OVERFLOW;
  300. OPENSSL_PUT_ERROR(SSL, ssl3_get_record, SSL_R_PACKET_LENGTH_TOO_LONG);
  301. goto f_err;
  302. }
  303. /* now s->rstate == SSL_ST_READ_BODY */
  304. }
  305. /* s->rstate == SSL_ST_READ_BODY, get and decode the data */
  306. if (rr->length > s->packet_length - SSL3_RT_HEADER_LENGTH) {
  307. /* now s->packet_length == SSL3_RT_HEADER_LENGTH */
  308. i = rr->length;
  309. n = ssl3_read_n(s, i, i, 1);
  310. if (n <= 0) {
  311. /* Error or non-blocking IO. Now |n| == |rr->length|, and
  312. * |s->packet_length| == |SSL3_RT_HEADER_LENGTH| + |rr->length|. */
  313. return n;
  314. }
  315. }
  316. s->rstate = SSL_ST_READ_HEADER; /* set state for later operations */
  317. /* At this point, s->packet_length == SSL3_RT_HEADER_LNGTH + rr->length, and
  318. * we have that many bytes in s->packet. */
  319. rr->input = &s->packet[SSL3_RT_HEADER_LENGTH];
  320. /* ok, we can now read from |s->packet| data into |rr|. |rr->input| points at
  321. * |rr->length| bytes, which need to be copied into |rr->data| by decryption.
  322. * When the data is 'copied' into the |rr->data| buffer, |rr->input| will be
  323. * pointed at the new buffer. */
  324. /* We now have - encrypted [ MAC [ compressed [ plain ] ] ]
  325. * rr->length bytes of encrypted compressed stuff. */
  326. /* check is not needed I believe */
  327. if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH + extra) {
  328. al = SSL_AD_RECORD_OVERFLOW;
  329. OPENSSL_PUT_ERROR(SSL, ssl3_get_record, SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
  330. goto f_err;
  331. }
  332. /* decrypt in place in 'rr->input' */
  333. rr->data = rr->input;
  334. if (!s->enc_method->enc(s, 0)) {
  335. al = SSL_AD_BAD_RECORD_MAC;
  336. OPENSSL_PUT_ERROR(SSL, ssl3_get_record,
  337. SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
  338. goto f_err;
  339. }
  340. if (rr->length > SSL3_RT_MAX_PLAIN_LENGTH + extra) {
  341. al = SSL_AD_RECORD_OVERFLOW;
  342. OPENSSL_PUT_ERROR(SSL, ssl3_get_record, SSL_R_DATA_LENGTH_TOO_LONG);
  343. goto f_err;
  344. }
  345. rr->off = 0;
  346. /* So at this point the following is true:
  347. * ssl->s3->rrec.type is the type of record;
  348. * ssl->s3->rrec.length is the number of bytes in the record;
  349. * ssl->s3->rrec.off is the offset to first valid byte;
  350. * ssl->s3->rrec.data is where to take bytes from (increment after use). */
  351. /* we have pulled in a full packet so zero things */
  352. s->packet_length = 0;
  353. /* just read a 0 length packet */
  354. if (rr->length == 0) {
  355. empty_record_count++;
  356. if (empty_record_count > MAX_EMPTY_RECORDS) {
  357. al = SSL_AD_UNEXPECTED_MESSAGE;
  358. OPENSSL_PUT_ERROR(SSL, ssl3_get_record, SSL_R_TOO_MANY_EMPTY_FRAGMENTS);
  359. goto f_err;
  360. }
  361. goto again;
  362. }
  363. return 1;
  364. f_err:
  365. ssl3_send_alert(s, SSL3_AL_FATAL, al);
  366. err:
  367. return ret;
  368. }
  369. /* Call this to write data in records of type |type|. It will return <= 0 if
  370. * not all data has been sent or non-blocking IO. */
  371. int ssl3_write_bytes(SSL *s, int type, const void *buf_, int len) {
  372. const uint8_t *buf = buf_;
  373. unsigned int tot, n, nw;
  374. int i;
  375. s->rwstate = SSL_NOTHING;
  376. assert(s->s3->wnum <= INT_MAX);
  377. tot = s->s3->wnum;
  378. s->s3->wnum = 0;
  379. if (SSL_in_init(s) && !s->in_handshake) {
  380. i = s->handshake_func(s);
  381. if (i < 0) {
  382. return i;
  383. }
  384. if (i == 0) {
  385. OPENSSL_PUT_ERROR(SSL, ssl3_write_bytes, SSL_R_SSL_HANDSHAKE_FAILURE);
  386. return -1;
  387. }
  388. }
  389. /* Ensure that if we end up with a smaller value of data to write out than
  390. * the the original len from a write which didn't complete for non-blocking
  391. * I/O and also somehow ended up avoiding the check for this in
  392. * ssl3_write_pending/SSL_R_BAD_WRITE_RETRY as it must never be possible to
  393. * end up with (len-tot) as a large number that will then promptly send
  394. * beyond the end of the users buffer ... so we trap and report the error in
  395. * a way the user will notice. */
  396. if (len < 0 || (size_t)len < tot) {
  397. OPENSSL_PUT_ERROR(SSL, ssl3_write_bytes, SSL_R_BAD_LENGTH);
  398. return -1;
  399. }
  400. n = (len - tot);
  401. for (;;) {
  402. /* max contains the maximum number of bytes that we can put into a
  403. * record. */
  404. unsigned max = s->max_send_fragment;
  405. /* fragment is true if do_ssl3_write should send the first byte in its own
  406. * record in order to randomise a CBC IV. */
  407. int fragment = 0;
  408. if (n > 1 && s->s3->need_record_splitting &&
  409. type == SSL3_RT_APPLICATION_DATA && !s->s3->record_split_done) {
  410. fragment = 1;
  411. /* record_split_done records that the splitting has been done in case we
  412. * hit an SSL_WANT_WRITE condition. In that case, we don't need to do the
  413. * split again. */
  414. s->s3->record_split_done = 1;
  415. }
  416. if (n > max) {
  417. nw = max;
  418. } else {
  419. nw = n;
  420. }
  421. i = do_ssl3_write(s, type, &(buf[tot]), nw, fragment, 0);
  422. if (i <= 0) {
  423. s->s3->wnum = tot;
  424. s->s3->record_split_done = 0;
  425. return i;
  426. }
  427. if (i == (int)n || (type == SSL3_RT_APPLICATION_DATA &&
  428. (s->mode & SSL_MODE_ENABLE_PARTIAL_WRITE))) {
  429. /* next chunk of data should get another prepended, one-byte fragment in
  430. * ciphersuites with known-IV weakness. */
  431. s->s3->record_split_done = 0;
  432. return tot + i;
  433. }
  434. n -= i;
  435. tot += i;
  436. }
  437. }
  438. /* do_ssl3_write writes an SSL record of the given type. If |fragment| is 1
  439. * then it splits the record into a one byte record and a record with the rest
  440. * of the data in order to randomise a CBC IV. If |is_fragment| is true then
  441. * this call resulted from do_ssl3_write calling itself in order to create that
  442. * one byte fragment. */
  443. static int do_ssl3_write(SSL *s, int type, const uint8_t *buf, unsigned int len,
  444. char fragment, char is_fragment) {
  445. uint8_t *p, *plen;
  446. int i;
  447. int prefix_len = 0;
  448. int eivlen = 0;
  449. long align = 0;
  450. SSL3_RECORD *wr;
  451. SSL3_BUFFER *wb = &(s->s3->wbuf);
  452. /* first check if there is a SSL3_BUFFER still being written out. This will
  453. * happen with non blocking IO */
  454. if (wb->left != 0) {
  455. return ssl3_write_pending(s, type, buf, len);
  456. }
  457. /* If we have an alert to send, lets send it */
  458. if (s->s3->alert_dispatch) {
  459. i = s->method->ssl_dispatch_alert(s);
  460. if (i <= 0) {
  461. return i;
  462. }
  463. /* if it went, fall through and send more stuff */
  464. }
  465. if (wb->buf == NULL && !ssl3_setup_write_buffer(s)) {
  466. return -1;
  467. }
  468. if (len == 0) {
  469. return 0;
  470. }
  471. wr = &s->s3->wrec;
  472. if (fragment) {
  473. /* countermeasure against known-IV weakness in CBC ciphersuites (see
  474. * http://www.openssl.org/~bodo/tls-cbc.txt) */
  475. prefix_len = do_ssl3_write(s, type, buf, 1 /* length */, 0 /* fragment */,
  476. 1 /* is_fragment */);
  477. if (prefix_len <= 0) {
  478. goto err;
  479. }
  480. if (prefix_len >
  481. (SSL3_RT_HEADER_LENGTH + SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD)) {
  482. /* insufficient space */
  483. OPENSSL_PUT_ERROR(SSL, do_ssl3_write, ERR_R_INTERNAL_ERROR);
  484. goto err;
  485. }
  486. }
  487. if (is_fragment) {
  488. /* The extra fragment would be couple of cipher blocks, and that will be a
  489. * multiple of SSL3_ALIGN_PAYLOAD. So, if we want to align the real
  490. * payload, we can just pretend that we have two headers and a byte. */
  491. align = (long)wb->buf + 2 * SSL3_RT_HEADER_LENGTH + 1;
  492. align = (-align) & (SSL3_ALIGN_PAYLOAD - 1);
  493. p = wb->buf + align;
  494. wb->offset = align;
  495. } else if (prefix_len) {
  496. p = wb->buf + wb->offset + prefix_len;
  497. } else {
  498. align = (long)wb->buf + SSL3_RT_HEADER_LENGTH;
  499. align = (-align) & (SSL3_ALIGN_PAYLOAD - 1);
  500. p = wb->buf + align;
  501. wb->offset = align;
  502. }
  503. /* write the header */
  504. *(p++) = type & 0xff;
  505. wr->type = type;
  506. /* Some servers hang if initial ClientHello is larger than 256 bytes and
  507. * record version number > TLS 1.0. */
  508. if (!s->s3->have_version && s->version > SSL3_VERSION) {
  509. *(p++) = TLS1_VERSION >> 8;
  510. *(p++) = TLS1_VERSION & 0xff;
  511. } else {
  512. *(p++) = s->version >> 8;
  513. *(p++) = s->version & 0xff;
  514. }
  515. /* field where we are to write out packet length */
  516. plen = p;
  517. p += 2;
  518. /* Leave room for the variable nonce for AEADs which specify it explicitly. */
  519. if (s->aead_write_ctx != NULL &&
  520. s->aead_write_ctx->variable_nonce_included_in_record) {
  521. eivlen = s->aead_write_ctx->variable_nonce_len;
  522. }
  523. /* lets setup the record stuff. */
  524. wr->data = p + eivlen;
  525. wr->length = (int)(len - (fragment != 0));
  526. wr->input = (uint8_t *)buf + (fragment != 0);
  527. /* we now 'read' from wr->input, wr->length bytes into wr->data */
  528. memcpy(wr->data, wr->input, wr->length);
  529. wr->input = wr->data;
  530. /* we should still have the output to wr->data and the input from wr->input.
  531. * Length should be wr->length. wr->data still points in the wb->buf */
  532. wr->input = p;
  533. wr->data = p;
  534. wr->length += eivlen;
  535. if (!s->enc_method->enc(s, 1)) {
  536. goto err;
  537. }
  538. /* record length after mac and block padding */
  539. s2n(wr->length, plen);
  540. if (s->msg_callback) {
  541. s->msg_callback(1, 0, SSL3_RT_HEADER, plen - 5, 5, s, s->msg_callback_arg);
  542. }
  543. /* we should now have wr->data pointing to the encrypted data, which is
  544. * wr->length long. */
  545. wr->type = type; /* not needed but helps for debugging */
  546. wr->length += SSL3_RT_HEADER_LENGTH;
  547. if (is_fragment) {
  548. /* we are in a recursive call; just return the length, don't write out
  549. * anything. */
  550. return wr->length;
  551. }
  552. /* now let's set up wb */
  553. wb->left = prefix_len + wr->length;
  554. /* memorize arguments so that ssl3_write_pending can detect bad write retries
  555. * later */
  556. s->s3->wpend_tot = len;
  557. s->s3->wpend_buf = buf;
  558. s->s3->wpend_type = type;
  559. s->s3->wpend_ret = len;
  560. /* we now just need to write the buffer */
  561. return ssl3_write_pending(s, type, buf, len);
  562. err:
  563. return -1;
  564. }
  565. /* if s->s3->wbuf.left != 0, we need to call this */
  566. int ssl3_write_pending(SSL *s, int type, const uint8_t *buf, unsigned int len) {
  567. int i;
  568. SSL3_BUFFER *wb = &(s->s3->wbuf);
  569. if (s->s3->wpend_tot > (int)len ||
  570. (s->s3->wpend_buf != buf &&
  571. !(s->mode & SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER)) ||
  572. s->s3->wpend_type != type) {
  573. OPENSSL_PUT_ERROR(SSL, ssl3_write_pending, SSL_R_BAD_WRITE_RETRY);
  574. return -1;
  575. }
  576. for (;;) {
  577. ERR_clear_system_error();
  578. if (s->wbio != NULL) {
  579. s->rwstate = SSL_WRITING;
  580. i = BIO_write(s->wbio, (char *)&(wb->buf[wb->offset]),
  581. (unsigned int)wb->left);
  582. } else {
  583. OPENSSL_PUT_ERROR(SSL, ssl3_write_pending, SSL_R_BIO_NOT_SET);
  584. i = -1;
  585. }
  586. if (i == wb->left) {
  587. wb->left = 0;
  588. wb->offset += i;
  589. if (s->mode & SSL_MODE_RELEASE_BUFFERS && !SSL_IS_DTLS(s)) {
  590. ssl3_release_write_buffer(s);
  591. }
  592. s->rwstate = SSL_NOTHING;
  593. return s->s3->wpend_ret;
  594. } else if (i <= 0) {
  595. if (SSL_IS_DTLS(s)) {
  596. /* For DTLS, just drop it. That's kind of the whole
  597. point in using a datagram service */
  598. wb->left = 0;
  599. }
  600. return i;
  601. }
  602. wb->offset += i;
  603. wb->left -= i;
  604. }
  605. }
  606. /* ssl3_expect_change_cipher_spec informs the record layer that a
  607. * ChangeCipherSpec record is required at this point. If a Handshake record is
  608. * received before ChangeCipherSpec, the connection will fail. Moreover, if
  609. * there are unprocessed handshake bytes, the handshake will also fail and the
  610. * function returns zero. Otherwise, the function returns one. */
  611. int ssl3_expect_change_cipher_spec(SSL *s) {
  612. if (s->s3->handshake_fragment_len > 0 || s->s3->tmp.reuse_message) {
  613. OPENSSL_PUT_ERROR(SSL, ssl3_expect_change_cipher_spec,
  614. SSL_R_UNPROCESSED_HANDSHAKE_DATA);
  615. return 0;
  616. }
  617. s->s3->flags |= SSL3_FLAGS_EXPECT_CCS;
  618. return 1;
  619. }
  620. /* Return up to 'len' payload bytes received in 'type' records.
  621. * 'type' is one of the following:
  622. *
  623. * - SSL3_RT_HANDSHAKE (when ssl3_get_message calls us)
  624. * - SSL3_RT_APPLICATION_DATA (when ssl3_read calls us)
  625. * - 0 (during a shutdown, no data has to be returned)
  626. *
  627. * If we don't have stored data to work from, read a SSL/TLS record first
  628. * (possibly multiple records if we still don't have anything to return).
  629. *
  630. * This function must handle any surprises the peer may have for us, such as
  631. * Alert records (e.g. close_notify), ChangeCipherSpec records (not really
  632. * a surprise, but handled as if it were), or renegotiation requests.
  633. * Also if record payloads contain fragments too small to process, we store
  634. * them until there is enough for the respective protocol (the record protocol
  635. * may use arbitrary fragmentation and even interleaving):
  636. * Change cipher spec protocol
  637. * just 1 byte needed, no need for keeping anything stored
  638. * Alert protocol
  639. * 2 bytes needed (AlertLevel, AlertDescription)
  640. * Handshake protocol
  641. * 4 bytes needed (HandshakeType, uint24 length) -- we just have
  642. * to detect unexpected Client Hello and Hello Request messages
  643. * here, anything else is handled by higher layers
  644. * Application data protocol
  645. * none of our business
  646. */
  647. int ssl3_read_bytes(SSL *s, int type, uint8_t *buf, int len, int peek) {
  648. int al, i, j, ret;
  649. unsigned int n;
  650. SSL3_RECORD *rr;
  651. void (*cb)(const SSL *ssl, int type2, int val) = NULL;
  652. uint8_t alert_buffer[2];
  653. if (s->s3->rbuf.buf == NULL && !ssl3_setup_read_buffer(s)) {
  654. return -1;
  655. }
  656. if ((type && type != SSL3_RT_APPLICATION_DATA && type != SSL3_RT_HANDSHAKE) ||
  657. (peek && type != SSL3_RT_APPLICATION_DATA)) {
  658. OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, ERR_R_INTERNAL_ERROR);
  659. return -1;
  660. }
  661. if (type == SSL3_RT_HANDSHAKE && s->s3->handshake_fragment_len > 0) {
  662. /* (partially) satisfy request from storage */
  663. uint8_t *src = s->s3->handshake_fragment;
  664. uint8_t *dst = buf;
  665. unsigned int k;
  666. /* peek == 0 */
  667. n = 0;
  668. while (len > 0 && s->s3->handshake_fragment_len > 0) {
  669. *dst++ = *src++;
  670. len--;
  671. s->s3->handshake_fragment_len--;
  672. n++;
  673. }
  674. /* move any remaining fragment bytes: */
  675. for (k = 0; k < s->s3->handshake_fragment_len; k++) {
  676. s->s3->handshake_fragment[k] = *src++;
  677. }
  678. return n;
  679. }
  680. /* Now s->s3->handshake_fragment_len == 0 if type == SSL3_RT_HANDSHAKE. */
  681. if (!s->in_handshake && SSL_in_init(s)) {
  682. /* type == SSL3_RT_APPLICATION_DATA */
  683. i = s->handshake_func(s);
  684. if (i < 0) {
  685. return i;
  686. }
  687. if (i == 0) {
  688. OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_SSL_HANDSHAKE_FAILURE);
  689. return -1;
  690. }
  691. }
  692. start:
  693. s->rwstate = SSL_NOTHING;
  694. /* s->s3->rrec.type - is the type of record
  695. * s->s3->rrec.data - data
  696. * s->s3->rrec.off - offset into 'data' for next read
  697. * s->s3->rrec.length - number of bytes. */
  698. rr = &s->s3->rrec;
  699. /* get new packet if necessary */
  700. if (rr->length == 0 || s->rstate == SSL_ST_READ_BODY) {
  701. ret = ssl3_get_record(s);
  702. if (ret <= 0) {
  703. return ret;
  704. }
  705. }
  706. /* we now have a packet which can be read and processed */
  707. if (s->s3->change_cipher_spec /* set when we receive ChangeCipherSpec,
  708. * reset by ssl3_get_finished */
  709. && rr->type != SSL3_RT_HANDSHAKE) {
  710. al = SSL_AD_UNEXPECTED_MESSAGE;
  711. OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes,
  712. SSL_R_DATA_BETWEEN_CCS_AND_FINISHED);
  713. goto f_err;
  714. }
  715. /* If we are expecting a ChangeCipherSpec, it is illegal to receive a
  716. * Handshake record. */
  717. if (rr->type == SSL3_RT_HANDSHAKE && (s->s3->flags & SSL3_FLAGS_EXPECT_CCS)) {
  718. al = SSL_AD_UNEXPECTED_MESSAGE;
  719. OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_HANDSHAKE_RECORD_BEFORE_CCS);
  720. goto f_err;
  721. }
  722. /* If the other end has shut down, throw anything we read away (even in
  723. * 'peek' mode) */
  724. if (s->shutdown & SSL_RECEIVED_SHUTDOWN) {
  725. rr->length = 0;
  726. s->rwstate = SSL_NOTHING;
  727. return 0;
  728. }
  729. if (type == rr->type) {
  730. /* SSL3_RT_APPLICATION_DATA or SSL3_RT_HANDSHAKE */
  731. /* make sure that we are not getting application data when we are doing a
  732. * handshake for the first time */
  733. if (SSL_in_init(s) && type == SSL3_RT_APPLICATION_DATA &&
  734. s->aead_read_ctx == NULL) {
  735. /* TODO(davidben): Is this check redundant with the handshake_func
  736. * check? */
  737. al = SSL_AD_UNEXPECTED_MESSAGE;
  738. OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_APP_DATA_IN_HANDSHAKE);
  739. goto f_err;
  740. }
  741. if (len <= 0) {
  742. return len;
  743. }
  744. if ((unsigned int)len > rr->length) {
  745. n = rr->length;
  746. } else {
  747. n = (unsigned int)len;
  748. }
  749. memcpy(buf, &(rr->data[rr->off]), n);
  750. if (!peek) {
  751. rr->length -= n;
  752. rr->off += n;
  753. if (rr->length == 0) {
  754. s->rstate = SSL_ST_READ_HEADER;
  755. rr->off = 0;
  756. if (s->mode & SSL_MODE_RELEASE_BUFFERS && s->s3->rbuf.left == 0) {
  757. ssl3_release_read_buffer(s);
  758. }
  759. }
  760. }
  761. return n;
  762. }
  763. /* If we get here, then type != rr->type; if we have a handshake message,
  764. * then it was unexpected (Hello Request or Client Hello). */
  765. /* In case of record types for which we have 'fragment' storage, fill that so
  766. * that we can process the data at a fixed place. */
  767. if (rr->type == SSL3_RT_HANDSHAKE) {
  768. const size_t size = sizeof(s->s3->handshake_fragment);
  769. const size_t avail = size - s->s3->handshake_fragment_len;
  770. const size_t todo = (rr->length < avail) ? rr->length : avail;
  771. memcpy(s->s3->handshake_fragment + s->s3->handshake_fragment_len,
  772. &rr->data[rr->off], todo);
  773. rr->off += todo;
  774. rr->length -= todo;
  775. s->s3->handshake_fragment_len += todo;
  776. if (s->s3->handshake_fragment_len < size) {
  777. goto start; /* fragment was too small */
  778. }
  779. } else if (rr->type == SSL3_RT_ALERT) {
  780. /* Note that this will still allow multiple alerts to be processed in the
  781. * same record */
  782. if (rr->length < sizeof(alert_buffer)) {
  783. al = SSL_AD_DECODE_ERROR;
  784. OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_BAD_ALERT);
  785. goto f_err;
  786. }
  787. memcpy(alert_buffer, &rr->data[rr->off], sizeof(alert_buffer));
  788. rr->off += sizeof(alert_buffer);
  789. rr->length -= sizeof(alert_buffer);
  790. }
  791. /* s->s3->handshake_fragment_len == 4 iff rr->type == SSL3_RT_HANDSHAKE;
  792. * (Possibly rr is 'empty' now, i.e. rr->length may be 0.) */
  793. /* If we are a client, check for an incoming 'Hello Request': */
  794. if (!s->server && s->s3->handshake_fragment_len >= 4 &&
  795. s->s3->handshake_fragment[0] == SSL3_MT_HELLO_REQUEST &&
  796. s->session != NULL && s->session->cipher != NULL) {
  797. s->s3->handshake_fragment_len = 0;
  798. if (s->s3->handshake_fragment[1] != 0 ||
  799. s->s3->handshake_fragment[2] != 0 ||
  800. s->s3->handshake_fragment[3] != 0) {
  801. al = SSL_AD_DECODE_ERROR;
  802. OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_BAD_HELLO_REQUEST);
  803. goto f_err;
  804. }
  805. if (s->msg_callback) {
  806. s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
  807. s->s3->handshake_fragment, 4, s, s->msg_callback_arg);
  808. }
  809. if (SSL_is_init_finished(s) && !s->s3->renegotiate) {
  810. ssl3_renegotiate(s);
  811. if (ssl3_renegotiate_check(s)) {
  812. i = s->handshake_func(s);
  813. if (i < 0) {
  814. return i;
  815. }
  816. if (i == 0) {
  817. OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_SSL_HANDSHAKE_FAILURE);
  818. return -1;
  819. }
  820. }
  821. }
  822. /* we either finished a handshake or ignored the request, now try again to
  823. * obtain the (application) data we were asked for */
  824. goto start;
  825. }
  826. if (rr->type == SSL3_RT_ALERT) {
  827. const uint8_t alert_level = alert_buffer[0];
  828. const uint8_t alert_descr = alert_buffer[1];
  829. if (s->msg_callback) {
  830. s->msg_callback(0, s->version, SSL3_RT_ALERT, alert_buffer, 2, s,
  831. s->msg_callback_arg);
  832. }
  833. if (s->info_callback != NULL) {
  834. cb = s->info_callback;
  835. } else if (s->ctx->info_callback != NULL) {
  836. cb = s->ctx->info_callback;
  837. }
  838. if (cb != NULL) {
  839. j = (alert_level << 8) | alert_descr;
  840. cb(s, SSL_CB_READ_ALERT, j);
  841. }
  842. if (alert_level == 1) {
  843. /* warning */
  844. s->s3->warn_alert = alert_descr;
  845. if (alert_descr == SSL_AD_CLOSE_NOTIFY) {
  846. s->shutdown |= SSL_RECEIVED_SHUTDOWN;
  847. return 0;
  848. }
  849. /* This is a warning but we receive it if we requested renegotiation and
  850. * the peer denied it. Terminate with a fatal alert because if
  851. * application tried to renegotiatie it presumably had a good reason and
  852. * expects it to succeed.
  853. *
  854. * In future we might have a renegotiation where we don't care if the
  855. * peer refused it where we carry on. */
  856. else if (alert_descr == SSL_AD_NO_RENEGOTIATION) {
  857. al = SSL_AD_HANDSHAKE_FAILURE;
  858. OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_NO_RENEGOTIATION);
  859. goto f_err;
  860. }
  861. } else if (alert_level == 2) {
  862. /* fatal */
  863. char tmp[16];
  864. s->rwstate = SSL_NOTHING;
  865. s->s3->fatal_alert = alert_descr;
  866. OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes,
  867. SSL_AD_REASON_OFFSET + alert_descr);
  868. BIO_snprintf(tmp, sizeof(tmp), "%d", alert_descr);
  869. ERR_add_error_data(2, "SSL alert number ", tmp);
  870. s->shutdown |= SSL_RECEIVED_SHUTDOWN;
  871. SSL_CTX_remove_session(s->ctx, s->session);
  872. return 0;
  873. } else {
  874. al = SSL_AD_ILLEGAL_PARAMETER;
  875. OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_UNKNOWN_ALERT_TYPE);
  876. goto f_err;
  877. }
  878. goto start;
  879. }
  880. if (s->shutdown & SSL_SENT_SHUTDOWN) {
  881. /* but we have not received a shutdown */
  882. s->rwstate = SSL_NOTHING;
  883. rr->length = 0;
  884. return 0;
  885. }
  886. if (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC) {
  887. /* 'Change Cipher Spec' is just a single byte, so we know exactly what the
  888. * record payload has to look like */
  889. if (rr->length != 1 || rr->off != 0 || rr->data[0] != SSL3_MT_CCS) {
  890. al = SSL_AD_ILLEGAL_PARAMETER;
  891. OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_BAD_CHANGE_CIPHER_SPEC);
  892. goto f_err;
  893. }
  894. /* Check we have a cipher to change to */
  895. if (s->s3->tmp.new_cipher == NULL) {
  896. al = SSL_AD_UNEXPECTED_MESSAGE;
  897. OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_CCS_RECEIVED_EARLY);
  898. goto f_err;
  899. }
  900. if (!(s->s3->flags & SSL3_FLAGS_EXPECT_CCS)) {
  901. al = SSL_AD_UNEXPECTED_MESSAGE;
  902. OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_CCS_RECEIVED_EARLY);
  903. goto f_err;
  904. }
  905. s->s3->flags &= ~SSL3_FLAGS_EXPECT_CCS;
  906. rr->length = 0;
  907. if (s->msg_callback) {
  908. s->msg_callback(0, s->version, SSL3_RT_CHANGE_CIPHER_SPEC, rr->data, 1, s,
  909. s->msg_callback_arg);
  910. }
  911. s->s3->change_cipher_spec = 1;
  912. if (!ssl3_do_change_cipher_spec(s)) {
  913. goto err;
  914. } else {
  915. goto start;
  916. }
  917. }
  918. /* Unexpected handshake message (Client Hello, or protocol violation) */
  919. if (s->s3->handshake_fragment_len >= 4 && !s->in_handshake) {
  920. if ((s->state & SSL_ST_MASK) == SSL_ST_OK) {
  921. s->state = s->server ? SSL_ST_ACCEPT : SSL_ST_CONNECT;
  922. s->renegotiate = 1;
  923. s->new_session = 1;
  924. }
  925. i = s->handshake_func(s);
  926. if (i < 0) {
  927. return i;
  928. }
  929. if (i == 0) {
  930. OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_SSL_HANDSHAKE_FAILURE);
  931. return -1;
  932. }
  933. goto start;
  934. }
  935. switch (rr->type) {
  936. default:
  937. /* TLS up to v1.1 just ignores unknown message types. TLS v1.2 gives an
  938. * unexpected message alert. */
  939. if (s->version >= TLS1_VERSION && s->version <= TLS1_1_VERSION) {
  940. rr->length = 0;
  941. goto start;
  942. }
  943. al = SSL_AD_UNEXPECTED_MESSAGE;
  944. OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_UNEXPECTED_RECORD);
  945. goto f_err;
  946. case SSL3_RT_CHANGE_CIPHER_SPEC:
  947. case SSL3_RT_ALERT:
  948. case SSL3_RT_HANDSHAKE:
  949. /* we already handled all of these, with the possible exception of
  950. * SSL3_RT_HANDSHAKE when s->in_handshake is set, but that should not
  951. * happen when type != rr->type */
  952. al = SSL_AD_UNEXPECTED_MESSAGE;
  953. OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, ERR_R_INTERNAL_ERROR);
  954. goto f_err;
  955. case SSL3_RT_APPLICATION_DATA:
  956. /* At this point we were expecting handshake data but have application
  957. * data. If the library was running inside ssl3_read() (i.e.
  958. * |in_read_app_data| is set) and it makes sense to read application data
  959. * at this point (session renegotiation not yet started), we will indulge
  960. * it. */
  961. if (s->s3->in_read_app_data && s->s3->total_renegotiations != 0 &&
  962. (((s->state & SSL_ST_CONNECT) &&
  963. s->state >= SSL3_ST_CW_CLNT_HELLO_A &&
  964. s->state <= SSL3_ST_CR_SRVR_HELLO_A) ||
  965. ((s->state & SSL_ST_ACCEPT) &&
  966. s->state <= SSL3_ST_SW_HELLO_REQ_A &&
  967. s->state >= SSL3_ST_SR_CLNT_HELLO_A))) {
  968. s->s3->in_read_app_data = 2;
  969. return -1;
  970. } else {
  971. al = SSL_AD_UNEXPECTED_MESSAGE;
  972. OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_UNEXPECTED_RECORD);
  973. goto f_err;
  974. }
  975. }
  976. /* not reached */
  977. f_err:
  978. ssl3_send_alert(s, SSL3_AL_FATAL, al);
  979. err:
  980. return -1;
  981. }
  982. int ssl3_do_change_cipher_spec(SSL *s) {
  983. int i;
  984. if (s->state & SSL_ST_ACCEPT) {
  985. i = SSL3_CHANGE_CIPHER_SERVER_READ;
  986. } else {
  987. i = SSL3_CHANGE_CIPHER_CLIENT_READ;
  988. }
  989. if (s->s3->tmp.key_block == NULL) {
  990. if (s->session == NULL || s->session->master_key_length == 0) {
  991. /* might happen if dtls1_read_bytes() calls this */
  992. OPENSSL_PUT_ERROR(SSL, ssl3_do_change_cipher_spec,
  993. SSL_R_CCS_RECEIVED_EARLY);
  994. return 0;
  995. }
  996. s->session->cipher = s->s3->tmp.new_cipher;
  997. if (!s->enc_method->setup_key_block(s)) {
  998. return 0;
  999. }
  1000. }
  1001. if (!s->enc_method->change_cipher_state(s, i)) {
  1002. return 0;
  1003. }
  1004. return 1;
  1005. }
  1006. int ssl3_send_alert(SSL *s, int level, int desc) {
  1007. /* Map tls/ssl alert value to correct one */
  1008. desc = s->enc_method->alert_value(desc);
  1009. if (s->version == SSL3_VERSION && desc == SSL_AD_PROTOCOL_VERSION) {
  1010. /* SSL 3.0 does not have protocol_version alerts */
  1011. desc = SSL_AD_HANDSHAKE_FAILURE;
  1012. }
  1013. if (desc < 0) {
  1014. return -1;
  1015. }
  1016. /* If a fatal one, remove from cache */
  1017. if (level == 2 && s->session != NULL) {
  1018. SSL_CTX_remove_session(s->ctx, s->session);
  1019. }
  1020. s->s3->alert_dispatch = 1;
  1021. s->s3->send_alert[0] = level;
  1022. s->s3->send_alert[1] = desc;
  1023. if (s->s3->wbuf.left == 0) {
  1024. /* data is still being written out. */
  1025. return s->method->ssl_dispatch_alert(s);
  1026. }
  1027. /* else data is still being written out, we will get written some time in the
  1028. * future */
  1029. return -1;
  1030. }
  1031. int ssl3_dispatch_alert(SSL *s) {
  1032. int i, j;
  1033. void (*cb)(const SSL *ssl, int type, int val) = NULL;
  1034. s->s3->alert_dispatch = 0;
  1035. i = do_ssl3_write(s, SSL3_RT_ALERT, &s->s3->send_alert[0], 2, 0, 0);
  1036. if (i <= 0) {
  1037. s->s3->alert_dispatch = 1;
  1038. } else {
  1039. /* Alert sent to BIO. If it is important, flush it now. If the message
  1040. * does not get sent due to non-blocking IO, we will not worry too much. */
  1041. if (s->s3->send_alert[0] == SSL3_AL_FATAL) {
  1042. BIO_flush(s->wbio);
  1043. }
  1044. if (s->msg_callback) {
  1045. s->msg_callback(1, s->version, SSL3_RT_ALERT, s->s3->send_alert, 2, s,
  1046. s->msg_callback_arg);
  1047. }
  1048. if (s->info_callback != NULL) {
  1049. cb = s->info_callback;
  1050. } else if (s->ctx->info_callback != NULL) {
  1051. cb = s->ctx->info_callback;
  1052. }
  1053. if (cb != NULL) {
  1054. j = (s->s3->send_alert[0] << 8) | s->s3->send_alert[1];
  1055. cb(s, SSL_CB_WRITE_ALERT, j);
  1056. }
  1057. }
  1058. return i;
  1059. }