25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.
 
 
 
 
 
 

1189 satır
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 <limits.h>
  110. #include <stdio.h>
  111. #include <string.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 "internal.h"
  118. static int do_ssl3_write(SSL *s, int type, const uint8_t *buf, unsigned int len,
  119. char 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. uintptr_t 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 = (uintptr_t)rb->buf + SSL3_RT_HEADER_LENGTH;
  142. align = (0 - 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. if (n > (int)(rb->len - rb->offset)) {
  189. OPENSSL_PUT_ERROR(SSL, ssl3_read_n, ERR_R_INTERNAL_ERROR);
  190. return -1;
  191. }
  192. if (!s->read_ahead) {
  193. /* ignore max parameter */
  194. max = n;
  195. } else {
  196. if (max < n) {
  197. max = n;
  198. }
  199. if (max > (int)(rb->len - rb->offset)) {
  200. max = rb->len - rb->offset;
  201. }
  202. }
  203. while (left < n) {
  204. /* Now we have len+left bytes at the front of s->s3->rbuf.buf and need to
  205. * read in more until we have len+n (up to len+max if possible). */
  206. ERR_clear_system_error();
  207. if (s->rbio != NULL) {
  208. s->rwstate = SSL_READING;
  209. i = BIO_read(s->rbio, pkt + len + left, max - left);
  210. } else {
  211. OPENSSL_PUT_ERROR(SSL, ssl3_read_n, SSL_R_READ_BIO_NOT_SET);
  212. i = -1;
  213. }
  214. if (i <= 0) {
  215. rb->left = left;
  216. if (s->mode & SSL_MODE_RELEASE_BUFFERS && !SSL_IS_DTLS(s) &&
  217. len + left == 0) {
  218. ssl3_release_read_buffer(s);
  219. }
  220. return i;
  221. }
  222. left += i;
  223. /* reads should *never* span multiple packets for DTLS because the
  224. * underlying transport protocol is message oriented as opposed to byte
  225. * oriented as in the TLS case. */
  226. if (SSL_IS_DTLS(s) && n > left) {
  227. n = left; /* makes the while condition false */
  228. }
  229. }
  230. /* done reading, now the book-keeping */
  231. rb->offset += n;
  232. rb->left = left - n;
  233. s->packet_length += n;
  234. s->rwstate = SSL_NOTHING;
  235. return n;
  236. }
  237. /* MAX_EMPTY_RECORDS defines the number of consecutive, empty records that will
  238. * be processed per call to ssl3_get_record. Without this limit an attacker
  239. * could send empty records at a faster rate than we can process and cause
  240. * ssl3_get_record to loop forever. */
  241. #define MAX_EMPTY_RECORDS 32
  242. /* Call this to get a new input record. It will return <= 0 if more data is
  243. * needed, normally due to an error or non-blocking IO. When it finishes, one
  244. * packet has been decoded and can be found in
  245. * ssl->s3->rrec.type - is the type of record
  246. * ssl->s3->rrec.data - data
  247. * ssl->s3->rrec.length - number of bytes */
  248. /* used only by ssl3_read_bytes */
  249. static int ssl3_get_record(SSL *s) {
  250. int ssl_major, ssl_minor, al;
  251. int n, i, ret = -1;
  252. SSL3_RECORD *rr;
  253. uint8_t *p;
  254. short version;
  255. size_t extra;
  256. unsigned empty_record_count = 0;
  257. rr = &s->s3->rrec;
  258. if (s->options & SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER) {
  259. extra = SSL3_RT_MAX_EXTRA;
  260. } else {
  261. extra = 0;
  262. }
  263. if (extra && !s->s3->init_extra) {
  264. /* An application error: SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER set after
  265. * ssl3_setup_buffers() was done */
  266. OPENSSL_PUT_ERROR(SSL, ssl3_get_record, ERR_R_INTERNAL_ERROR);
  267. return -1;
  268. }
  269. again:
  270. /* check if we have the header */
  271. if (s->rstate != SSL_ST_READ_BODY ||
  272. s->packet_length < SSL3_RT_HEADER_LENGTH) {
  273. n = ssl3_read_n(s, SSL3_RT_HEADER_LENGTH, s->s3->rbuf.len, 0);
  274. if (n <= 0) {
  275. return n; /* error or non-blocking */
  276. }
  277. s->rstate = SSL_ST_READ_BODY;
  278. p = s->packet;
  279. if (s->msg_callback) {
  280. s->msg_callback(0, 0, SSL3_RT_HEADER, p, 5, s, s->msg_callback_arg);
  281. }
  282. /* Pull apart the header into the SSL3_RECORD */
  283. rr->type = *(p++);
  284. ssl_major = *(p++);
  285. ssl_minor = *(p++);
  286. version = (ssl_major << 8) | ssl_minor;
  287. n2s(p, rr->length);
  288. if (s->s3->have_version && version != s->version) {
  289. OPENSSL_PUT_ERROR(SSL, ssl3_get_record, SSL_R_WRONG_VERSION_NUMBER);
  290. al = SSL_AD_PROTOCOL_VERSION;
  291. goto f_err;
  292. }
  293. if ((version >> 8) != SSL3_VERSION_MAJOR) {
  294. OPENSSL_PUT_ERROR(SSL, ssl3_get_record, SSL_R_WRONG_VERSION_NUMBER);
  295. goto err;
  296. }
  297. if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH + extra) {
  298. al = SSL_AD_RECORD_OVERFLOW;
  299. OPENSSL_PUT_ERROR(SSL, ssl3_get_record, SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
  300. goto f_err;
  301. }
  302. /* now s->rstate == SSL_ST_READ_BODY */
  303. }
  304. /* s->rstate == SSL_ST_READ_BODY, get and decode the data */
  305. if (rr->length > s->packet_length - SSL3_RT_HEADER_LENGTH) {
  306. /* now s->packet_length == SSL3_RT_HEADER_LENGTH */
  307. i = rr->length;
  308. n = ssl3_read_n(s, i, i, 1);
  309. if (n <= 0) {
  310. /* Error or non-blocking IO. Now |n| == |rr->length|, and
  311. * |s->packet_length| == |SSL3_RT_HEADER_LENGTH| + |rr->length|. */
  312. return n;
  313. }
  314. }
  315. s->rstate = SSL_ST_READ_HEADER; /* set state for later operations */
  316. /* At this point, s->packet_length == SSL3_RT_HEADER_LNGTH + rr->length, and
  317. * we have that many bytes in s->packet. */
  318. rr->input = &s->packet[SSL3_RT_HEADER_LENGTH];
  319. /* ok, we can now read from |s->packet| data into |rr|. |rr->input| points at
  320. * |rr->length| bytes, which need to be copied into |rr->data| by decryption.
  321. * When the data is 'copied' into the |rr->data| buffer, |rr->input| will be
  322. * pointed at the new buffer. */
  323. /* We now have - encrypted [ MAC [ compressed [ plain ] ] ]
  324. * rr->length bytes of encrypted compressed stuff. */
  325. /* decrypt in place in 'rr->input' */
  326. rr->data = rr->input;
  327. if (!s->enc_method->enc(s, 0)) {
  328. al = SSL_AD_BAD_RECORD_MAC;
  329. OPENSSL_PUT_ERROR(SSL, ssl3_get_record,
  330. SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
  331. goto f_err;
  332. }
  333. if (rr->length > SSL3_RT_MAX_PLAIN_LENGTH + extra) {
  334. al = SSL_AD_RECORD_OVERFLOW;
  335. OPENSSL_PUT_ERROR(SSL, ssl3_get_record, SSL_R_DATA_LENGTH_TOO_LONG);
  336. goto f_err;
  337. }
  338. rr->off = 0;
  339. /* So at this point the following is true:
  340. * ssl->s3->rrec.type is the type of record;
  341. * ssl->s3->rrec.length is the number of bytes in the record;
  342. * ssl->s3->rrec.off is the offset to first valid byte;
  343. * ssl->s3->rrec.data is where to take bytes from (increment after use). */
  344. /* we have pulled in a full packet so zero things */
  345. s->packet_length = 0;
  346. /* just read a 0 length packet */
  347. if (rr->length == 0) {
  348. empty_record_count++;
  349. if (empty_record_count > MAX_EMPTY_RECORDS) {
  350. al = SSL_AD_UNEXPECTED_MESSAGE;
  351. OPENSSL_PUT_ERROR(SSL, ssl3_get_record, SSL_R_TOO_MANY_EMPTY_FRAGMENTS);
  352. goto f_err;
  353. }
  354. goto again;
  355. }
  356. return 1;
  357. f_err:
  358. ssl3_send_alert(s, SSL3_AL_FATAL, al);
  359. err:
  360. return ret;
  361. }
  362. /* Call this to write data in records of type |type|. It will return <= 0 if
  363. * not all data has been sent or non-blocking IO. */
  364. int ssl3_write_bytes(SSL *s, int type, const void *buf_, int len) {
  365. const uint8_t *buf = buf_;
  366. unsigned int tot, n, nw;
  367. int i;
  368. s->rwstate = SSL_NOTHING;
  369. assert(s->s3->wnum <= INT_MAX);
  370. tot = s->s3->wnum;
  371. s->s3->wnum = 0;
  372. if (!s->in_handshake && SSL_in_init(s) && !SSL_in_false_start(s)) {
  373. i = s->handshake_func(s);
  374. if (i < 0) {
  375. return i;
  376. }
  377. if (i == 0) {
  378. OPENSSL_PUT_ERROR(SSL, ssl3_write_bytes, SSL_R_SSL_HANDSHAKE_FAILURE);
  379. return -1;
  380. }
  381. }
  382. /* Ensure that if we end up with a smaller value of data to write out than
  383. * the the original len from a write which didn't complete for non-blocking
  384. * I/O and also somehow ended up avoiding the check for this in
  385. * ssl3_write_pending/SSL_R_BAD_WRITE_RETRY as it must never be possible to
  386. * end up with (len-tot) as a large number that will then promptly send
  387. * beyond the end of the users buffer ... so we trap and report the error in
  388. * a way the user will notice. */
  389. if (len < 0 || (size_t)len < tot) {
  390. OPENSSL_PUT_ERROR(SSL, ssl3_write_bytes, SSL_R_BAD_LENGTH);
  391. return -1;
  392. }
  393. int record_split_done = 0;
  394. n = (len - tot);
  395. for (;;) {
  396. /* max contains the maximum number of bytes that we can put into a
  397. * record. */
  398. unsigned max = s->max_send_fragment;
  399. /* fragment is true if do_ssl3_write should send the first byte in its own
  400. * record in order to randomise a CBC IV. */
  401. int fragment = 0;
  402. if (!record_split_done && s->s3->need_record_splitting &&
  403. type == SSL3_RT_APPLICATION_DATA) {
  404. /* Only the the first record per write call needs to be split. The
  405. * remaining plaintext was determined before the IV was randomized. */
  406. fragment = 1;
  407. record_split_done = 1;
  408. }
  409. if (n > max) {
  410. nw = max;
  411. } else {
  412. nw = n;
  413. }
  414. i = do_ssl3_write(s, type, &buf[tot], nw, fragment);
  415. if (i <= 0) {
  416. s->s3->wnum = tot;
  417. return i;
  418. }
  419. if (i == (int)n || (type == SSL3_RT_APPLICATION_DATA &&
  420. (s->mode & SSL_MODE_ENABLE_PARTIAL_WRITE))) {
  421. return tot + i;
  422. }
  423. n -= i;
  424. tot += i;
  425. }
  426. }
  427. /* ssl3_seal_record seals a new record of type |type| and plaintext |in| and
  428. * writes it to |out|. At most |max_out| bytes will be written. It returns one
  429. * on success and zero on error. On success, |s->s3->wrec| is updated to include
  430. * the new record. */
  431. static int ssl3_seal_record(SSL *s, uint8_t *out, size_t *out_len,
  432. size_t max_out, uint8_t type, const uint8_t *in,
  433. size_t in_len) {
  434. if (max_out < SSL3_RT_HEADER_LENGTH) {
  435. OPENSSL_PUT_ERROR(SSL, ssl3_seal_record, SSL_R_BUFFER_TOO_SMALL);
  436. return 0;
  437. }
  438. out[0] = type;
  439. /* Some servers hang if initial ClientHello is larger than 256 bytes and
  440. * record version number > TLS 1.0. */
  441. if (!s->s3->have_version && s->version > SSL3_VERSION) {
  442. out[1] = TLS1_VERSION >> 8;
  443. out[2] = TLS1_VERSION & 0xff;
  444. } else {
  445. out[1] = s->version >> 8;
  446. out[2] = s->version & 0xff;
  447. }
  448. size_t explicit_nonce_len = 0;
  449. if (s->aead_write_ctx != NULL &&
  450. s->aead_write_ctx->variable_nonce_included_in_record) {
  451. explicit_nonce_len = s->aead_write_ctx->variable_nonce_len;
  452. }
  453. size_t max_overhead = 0;
  454. if (s->aead_write_ctx != NULL) {
  455. max_overhead = s->aead_write_ctx->tag_len;
  456. }
  457. /* Assemble the input for |s->enc_method->enc|. The input is the plaintext
  458. * with |explicit_nonce_len| bytes of space prepended for the explicit
  459. * nonce. The input is copied into |out| and then encrypted in-place to take
  460. * advantage of alignment.
  461. *
  462. * TODO(davidben): |tls1_enc| should accept its inputs and outputs directly
  463. * rather than looking up in |wrec| and friends. The |max_overhead| bounds
  464. * check would also be unnecessary if |max_out| were passed down. */
  465. SSL3_RECORD *wr = &s->s3->wrec;
  466. size_t plaintext_len = in_len + explicit_nonce_len;
  467. if (plaintext_len < in_len || plaintext_len > INT_MAX ||
  468. plaintext_len + max_overhead < plaintext_len) {
  469. OPENSSL_PUT_ERROR(SSL, ssl3_seal_record, ERR_R_OVERFLOW);
  470. return 0;
  471. }
  472. if (max_out - SSL3_RT_HEADER_LENGTH < plaintext_len + max_overhead) {
  473. OPENSSL_PUT_ERROR(SSL, ssl3_seal_record, SSL_R_BUFFER_TOO_SMALL);
  474. return 0;
  475. }
  476. wr->type = type;
  477. wr->input = out + SSL3_RT_HEADER_LENGTH;
  478. wr->data = wr->input;
  479. wr->length = plaintext_len;
  480. memcpy(wr->input + explicit_nonce_len, in, in_len);
  481. if (!s->enc_method->enc(s, 1)) {
  482. return 0;
  483. }
  484. /* |wr->length| has now been set to the ciphertext length. */
  485. if (wr->length >= 1 << 16) {
  486. OPENSSL_PUT_ERROR(SSL, ssl3_seal_record, ERR_R_OVERFLOW);
  487. return 0;
  488. }
  489. out[3] = wr->length >> 8;
  490. out[4] = wr->length & 0xff;
  491. *out_len = SSL3_RT_HEADER_LENGTH + (size_t)wr->length;
  492. if (s->msg_callback) {
  493. s->msg_callback(1 /* write */, 0, SSL3_RT_HEADER, out, SSL3_RT_HEADER_LENGTH,
  494. s, s->msg_callback_arg);
  495. }
  496. return 1;
  497. }
  498. /* do_ssl3_write writes an SSL record of the given type. If |fragment| is 1
  499. * then it splits the record into a one byte record and a record with the rest
  500. * of the data in order to randomise a CBC IV. */
  501. static int do_ssl3_write(SSL *s, int type, const uint8_t *buf, unsigned int len,
  502. char fragment) {
  503. SSL3_BUFFER *wb = &s->s3->wbuf;
  504. /* first check if there is a SSL3_BUFFER still being written out. This will
  505. * happen with non blocking IO */
  506. if (wb->left != 0) {
  507. return ssl3_write_pending(s, type, buf, len);
  508. }
  509. /* If we have an alert to send, lets send it */
  510. if (s->s3->alert_dispatch) {
  511. int ret = s->method->ssl_dispatch_alert(s);
  512. if (ret <= 0) {
  513. return ret;
  514. }
  515. /* if it went, fall through and send more stuff */
  516. }
  517. if (wb->buf == NULL && !ssl3_setup_write_buffer(s)) {
  518. return -1;
  519. }
  520. if (len == 0) {
  521. return 0;
  522. }
  523. if (len == 1) {
  524. /* No sense in fragmenting a one-byte record. */
  525. fragment = 0;
  526. }
  527. /* Align the output so the ciphertext is aligned to |SSL3_ALIGN_PAYLOAD|. */
  528. uintptr_t align;
  529. if (fragment) {
  530. /* Only CBC-mode ciphers require fragmenting. CBC-mode ciphertext is a
  531. * multiple of the block size which we may assume is aligned. Thus we only
  532. * need to account for a second copy of the record header. */
  533. align = (uintptr_t)wb->buf + 2 * SSL3_RT_HEADER_LENGTH;
  534. } else {
  535. align = (uintptr_t)wb->buf + SSL3_RT_HEADER_LENGTH;
  536. }
  537. align = (0 - align) & (SSL3_ALIGN_PAYLOAD - 1);
  538. uint8_t *out = wb->buf + align;
  539. wb->offset = align;
  540. size_t max_out = wb->len - wb->offset;
  541. const uint8_t *orig_buf = buf;
  542. unsigned int orig_len = len;
  543. size_t fragment_len = 0;
  544. if (fragment) {
  545. /* Write the first byte in its own record as a countermeasure against
  546. * known-IV weaknesses in CBC ciphersuites. (See
  547. * http://www.openssl.org/~bodo/tls-cbc.txt.) */
  548. if (!ssl3_seal_record(s, out, &fragment_len, max_out, type, buf, 1)) {
  549. return -1;
  550. }
  551. out += fragment_len;
  552. max_out -= fragment_len;
  553. buf++;
  554. len--;
  555. }
  556. assert((((uintptr_t)out + SSL3_RT_HEADER_LENGTH) & (SSL3_ALIGN_PAYLOAD - 1))
  557. == 0);
  558. size_t ciphertext_len;
  559. if (!ssl3_seal_record(s, out, &ciphertext_len, max_out, type, buf, len)) {
  560. return -1;
  561. }
  562. ciphertext_len += fragment_len;
  563. /* now let's set up wb */
  564. wb->left = ciphertext_len;
  565. /* memorize arguments so that ssl3_write_pending can detect bad write retries
  566. * later */
  567. s->s3->wpend_tot = orig_len;
  568. s->s3->wpend_buf = orig_buf;
  569. s->s3->wpend_type = type;
  570. s->s3->wpend_ret = orig_len;
  571. /* we now just need to write the buffer */
  572. return ssl3_write_pending(s, type, orig_buf, orig_len);
  573. }
  574. /* if s->s3->wbuf.left != 0, we need to call this */
  575. int ssl3_write_pending(SSL *s, int type, const uint8_t *buf, unsigned int len) {
  576. int i;
  577. SSL3_BUFFER *wb = &(s->s3->wbuf);
  578. if (s->s3->wpend_tot > (int)len ||
  579. (s->s3->wpend_buf != buf &&
  580. !(s->mode & SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER)) ||
  581. s->s3->wpend_type != type) {
  582. OPENSSL_PUT_ERROR(SSL, ssl3_write_pending, SSL_R_BAD_WRITE_RETRY);
  583. return -1;
  584. }
  585. for (;;) {
  586. ERR_clear_system_error();
  587. if (s->wbio != NULL) {
  588. s->rwstate = SSL_WRITING;
  589. i = BIO_write(s->wbio, (char *)&(wb->buf[wb->offset]),
  590. (unsigned int)wb->left);
  591. } else {
  592. OPENSSL_PUT_ERROR(SSL, ssl3_write_pending, SSL_R_BIO_NOT_SET);
  593. i = -1;
  594. }
  595. if (i == wb->left) {
  596. wb->left = 0;
  597. wb->offset += i;
  598. if (s->mode & SSL_MODE_RELEASE_BUFFERS && !SSL_IS_DTLS(s)) {
  599. ssl3_release_write_buffer(s);
  600. }
  601. s->rwstate = SSL_NOTHING;
  602. return s->s3->wpend_ret;
  603. } else if (i <= 0) {
  604. if (SSL_IS_DTLS(s)) {
  605. /* For DTLS, just drop it. That's kind of the whole
  606. point in using a datagram service */
  607. wb->left = 0;
  608. }
  609. return i;
  610. }
  611. /* TODO(davidben): This codepath is used in DTLS, but the write
  612. * payload may not split across packets. */
  613. wb->offset += i;
  614. wb->left -= i;
  615. }
  616. }
  617. /* ssl3_expect_change_cipher_spec informs the record layer that a
  618. * ChangeCipherSpec record is required at this point. If a Handshake record is
  619. * received before ChangeCipherSpec, the connection will fail. Moreover, if
  620. * there are unprocessed handshake bytes, the handshake will also fail and the
  621. * function returns zero. Otherwise, the function returns one. */
  622. int ssl3_expect_change_cipher_spec(SSL *s) {
  623. if (s->s3->handshake_fragment_len > 0 || s->s3->tmp.reuse_message) {
  624. OPENSSL_PUT_ERROR(SSL, ssl3_expect_change_cipher_spec,
  625. SSL_R_UNPROCESSED_HANDSHAKE_DATA);
  626. return 0;
  627. }
  628. s->s3->flags |= SSL3_FLAGS_EXPECT_CCS;
  629. return 1;
  630. }
  631. /* Return up to 'len' payload bytes received in 'type' records.
  632. * 'type' is one of the following:
  633. *
  634. * - SSL3_RT_HANDSHAKE (when ssl3_get_message calls us)
  635. * - SSL3_RT_APPLICATION_DATA (when ssl3_read calls us)
  636. * - 0 (during a shutdown, no data has to be returned)
  637. *
  638. * If we don't have stored data to work from, read a SSL/TLS record first
  639. * (possibly multiple records if we still don't have anything to return).
  640. *
  641. * This function must handle any surprises the peer may have for us, such as
  642. * Alert records (e.g. close_notify), ChangeCipherSpec records (not really
  643. * a surprise, but handled as if it were), or renegotiation requests.
  644. * Also if record payloads contain fragments too small to process, we store
  645. * them until there is enough for the respective protocol (the record protocol
  646. * may use arbitrary fragmentation and even interleaving):
  647. * Change cipher spec protocol
  648. * just 1 byte needed, no need for keeping anything stored
  649. * Alert protocol
  650. * 2 bytes needed (AlertLevel, AlertDescription)
  651. * Handshake protocol
  652. * 4 bytes needed (HandshakeType, uint24 length) -- we just have
  653. * to detect unexpected Client Hello and Hello Request messages
  654. * here, anything else is handled by higher layers
  655. * Application data protocol
  656. * none of our business
  657. */
  658. int ssl3_read_bytes(SSL *s, int type, uint8_t *buf, int len, int peek) {
  659. int al, i, ret;
  660. unsigned int n;
  661. SSL3_RECORD *rr;
  662. void (*cb)(const SSL *ssl, int type2, int val) = NULL;
  663. if ((type && type != SSL3_RT_APPLICATION_DATA && type != SSL3_RT_HANDSHAKE) ||
  664. (peek && type != SSL3_RT_APPLICATION_DATA)) {
  665. OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, ERR_R_INTERNAL_ERROR);
  666. return -1;
  667. }
  668. if (type == SSL3_RT_HANDSHAKE && s->s3->handshake_fragment_len > 0) {
  669. /* (partially) satisfy request from storage */
  670. uint8_t *src = s->s3->handshake_fragment;
  671. uint8_t *dst = buf;
  672. unsigned int k;
  673. /* peek == 0 */
  674. n = 0;
  675. while (len > 0 && s->s3->handshake_fragment_len > 0) {
  676. *dst++ = *src++;
  677. len--;
  678. s->s3->handshake_fragment_len--;
  679. n++;
  680. }
  681. /* move any remaining fragment bytes: */
  682. for (k = 0; k < s->s3->handshake_fragment_len; k++) {
  683. s->s3->handshake_fragment[k] = *src++;
  684. }
  685. return n;
  686. }
  687. /* Now s->s3->handshake_fragment_len == 0 if type == SSL3_RT_HANDSHAKE. */
  688. /* This may require multiple iterations. False Start will cause
  689. * |s->handshake_func| to signal success one step early, but the handshake
  690. * must be completely finished before other modes are accepted.
  691. *
  692. * TODO(davidben): Move this check up to a higher level. */
  693. while (!s->in_handshake && SSL_in_init(s)) {
  694. assert(type == SSL3_RT_APPLICATION_DATA);
  695. i = s->handshake_func(s);
  696. if (i < 0) {
  697. return i;
  698. }
  699. if (i == 0) {
  700. OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_SSL_HANDSHAKE_FAILURE);
  701. return -1;
  702. }
  703. }
  704. if (s->s3->rbuf.buf == NULL && !ssl3_setup_read_buffer(s)) {
  705. /* TODO(davidben): Is this redundant with the calls in the handshake? */
  706. return -1;
  707. }
  708. start:
  709. s->rwstate = SSL_NOTHING;
  710. /* s->s3->rrec.type - is the type of record
  711. * s->s3->rrec.data - data
  712. * s->s3->rrec.off - offset into 'data' for next read
  713. * s->s3->rrec.length - number of bytes. */
  714. rr = &s->s3->rrec;
  715. /* get new packet if necessary */
  716. if (rr->length == 0 || s->rstate == SSL_ST_READ_BODY) {
  717. ret = ssl3_get_record(s);
  718. if (ret <= 0) {
  719. return ret;
  720. }
  721. }
  722. /* we now have a packet which can be read and processed */
  723. /* |change_cipher_spec is set when we receive a ChangeCipherSpec and reset by
  724. * ssl3_get_finished. */
  725. if (s->s3->change_cipher_spec && rr->type != SSL3_RT_HANDSHAKE &&
  726. rr->type != SSL3_RT_ALERT) {
  727. al = SSL_AD_UNEXPECTED_MESSAGE;
  728. OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes,
  729. SSL_R_DATA_BETWEEN_CCS_AND_FINISHED);
  730. goto f_err;
  731. }
  732. /* If we are expecting a ChangeCipherSpec, it is illegal to receive a
  733. * Handshake record. */
  734. if (rr->type == SSL3_RT_HANDSHAKE && (s->s3->flags & SSL3_FLAGS_EXPECT_CCS)) {
  735. al = SSL_AD_UNEXPECTED_MESSAGE;
  736. OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_HANDSHAKE_RECORD_BEFORE_CCS);
  737. goto f_err;
  738. }
  739. /* If the other end has shut down, throw anything we read away (even in
  740. * 'peek' mode) */
  741. if (s->shutdown & SSL_RECEIVED_SHUTDOWN) {
  742. rr->length = 0;
  743. s->rwstate = SSL_NOTHING;
  744. return 0;
  745. }
  746. if (type == rr->type) {
  747. /* SSL3_RT_APPLICATION_DATA or SSL3_RT_HANDSHAKE */
  748. /* make sure that we are not getting application data when we are doing a
  749. * handshake for the first time */
  750. if (SSL_in_init(s) && type == SSL3_RT_APPLICATION_DATA &&
  751. s->aead_read_ctx == NULL) {
  752. /* TODO(davidben): Is this check redundant with the handshake_func
  753. * check? */
  754. al = SSL_AD_UNEXPECTED_MESSAGE;
  755. OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_APP_DATA_IN_HANDSHAKE);
  756. goto f_err;
  757. }
  758. if (len <= 0) {
  759. return len;
  760. }
  761. if ((unsigned int)len > rr->length) {
  762. n = rr->length;
  763. } else {
  764. n = (unsigned int)len;
  765. }
  766. memcpy(buf, &(rr->data[rr->off]), n);
  767. if (!peek) {
  768. rr->length -= n;
  769. rr->off += n;
  770. if (rr->length == 0) {
  771. s->rstate = SSL_ST_READ_HEADER;
  772. rr->off = 0;
  773. if (s->mode & SSL_MODE_RELEASE_BUFFERS && s->s3->rbuf.left == 0) {
  774. ssl3_release_read_buffer(s);
  775. }
  776. }
  777. }
  778. return n;
  779. }
  780. /* If we get here, then type != rr->type; if we have a handshake message,
  781. * then it was unexpected (Hello Request or Client Hello). */
  782. /* In case of record types for which we have 'fragment' storage, fill that so
  783. * that we can process the data at a fixed place. */
  784. if (rr->type == SSL3_RT_HANDSHAKE) {
  785. /* If peer renegotiations are disabled, all out-of-order handshake records
  786. * are fatal. */
  787. if (s->reject_peer_renegotiations) {
  788. al = SSL_AD_NO_RENEGOTIATION;
  789. OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_NO_RENEGOTIATION);
  790. goto f_err;
  791. }
  792. const size_t size = sizeof(s->s3->handshake_fragment);
  793. const size_t avail = size - s->s3->handshake_fragment_len;
  794. const size_t todo = (rr->length < avail) ? rr->length : avail;
  795. memcpy(s->s3->handshake_fragment + s->s3->handshake_fragment_len,
  796. &rr->data[rr->off], todo);
  797. rr->off += todo;
  798. rr->length -= todo;
  799. s->s3->handshake_fragment_len += todo;
  800. if (s->s3->handshake_fragment_len < size) {
  801. goto start; /* fragment was too small */
  802. }
  803. }
  804. /* s->s3->handshake_fragment_len == 4 iff rr->type == SSL3_RT_HANDSHAKE;
  805. * (Possibly rr is 'empty' now, i.e. rr->length may be 0.) */
  806. /* If we are a client, check for an incoming 'Hello Request': */
  807. if (!s->server && s->s3->handshake_fragment_len >= 4 &&
  808. s->s3->handshake_fragment[0] == SSL3_MT_HELLO_REQUEST &&
  809. s->session != NULL && s->session->cipher != NULL) {
  810. s->s3->handshake_fragment_len = 0;
  811. if (s->s3->handshake_fragment[1] != 0 ||
  812. s->s3->handshake_fragment[2] != 0 ||
  813. s->s3->handshake_fragment[3] != 0) {
  814. al = SSL_AD_DECODE_ERROR;
  815. OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_BAD_HELLO_REQUEST);
  816. goto f_err;
  817. }
  818. if (s->msg_callback) {
  819. s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
  820. s->s3->handshake_fragment, 4, s, s->msg_callback_arg);
  821. }
  822. if (SSL_is_init_finished(s) && !s->s3->renegotiate) {
  823. ssl3_renegotiate(s);
  824. if (ssl3_renegotiate_check(s)) {
  825. i = s->handshake_func(s);
  826. if (i < 0) {
  827. return i;
  828. }
  829. if (i == 0) {
  830. OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_SSL_HANDSHAKE_FAILURE);
  831. return -1;
  832. }
  833. }
  834. }
  835. /* we either finished a handshake or ignored the request, now try again to
  836. * obtain the (application) data we were asked for */
  837. goto start;
  838. }
  839. /* If an alert record, process one alert out of the record. Note that we allow
  840. * a single record to contain multiple alerts. */
  841. if (rr->type == SSL3_RT_ALERT) {
  842. /* Alerts may not be fragmented. */
  843. if (rr->length < 2) {
  844. al = SSL_AD_DECODE_ERROR;
  845. OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_BAD_ALERT);
  846. goto f_err;
  847. }
  848. if (s->msg_callback) {
  849. s->msg_callback(0, s->version, SSL3_RT_ALERT, &rr->data[rr->off], 2, s,
  850. s->msg_callback_arg);
  851. }
  852. const uint8_t alert_level = rr->data[rr->off++];
  853. const uint8_t alert_descr = rr->data[rr->off++];
  854. rr->length -= 2;
  855. if (s->info_callback != NULL) {
  856. cb = s->info_callback;
  857. } else if (s->ctx->info_callback != NULL) {
  858. cb = s->ctx->info_callback;
  859. }
  860. if (cb != NULL) {
  861. uint16_t alert = (alert_level << 8) | alert_descr;
  862. cb(s, SSL_CB_READ_ALERT, alert);
  863. }
  864. if (alert_level == SSL3_AL_WARNING) {
  865. s->s3->warn_alert = alert_descr;
  866. if (alert_descr == SSL_AD_CLOSE_NOTIFY) {
  867. s->shutdown |= SSL_RECEIVED_SHUTDOWN;
  868. return 0;
  869. }
  870. /* This is a warning but we receive it if we requested renegotiation and
  871. * the peer denied it. Terminate with a fatal alert because if
  872. * application tried to renegotiatie it presumably had a good reason and
  873. * expects it to succeed.
  874. *
  875. * In future we might have a renegotiation where we don't care if the
  876. * peer refused it where we carry on. */
  877. else if (alert_descr == SSL_AD_NO_RENEGOTIATION) {
  878. al = SSL_AD_HANDSHAKE_FAILURE;
  879. OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_NO_RENEGOTIATION);
  880. goto f_err;
  881. }
  882. } else if (alert_level == SSL3_AL_FATAL) {
  883. char tmp[16];
  884. s->rwstate = SSL_NOTHING;
  885. s->s3->fatal_alert = alert_descr;
  886. OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes,
  887. SSL_AD_REASON_OFFSET + alert_descr);
  888. BIO_snprintf(tmp, sizeof(tmp), "%d", alert_descr);
  889. ERR_add_error_data(2, "SSL alert number ", tmp);
  890. s->shutdown |= SSL_RECEIVED_SHUTDOWN;
  891. SSL_CTX_remove_session(s->ctx, s->session);
  892. return 0;
  893. } else {
  894. al = SSL_AD_ILLEGAL_PARAMETER;
  895. OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_UNKNOWN_ALERT_TYPE);
  896. goto f_err;
  897. }
  898. goto start;
  899. }
  900. if (s->shutdown & SSL_SENT_SHUTDOWN) {
  901. /* but we have not received a shutdown */
  902. s->rwstate = SSL_NOTHING;
  903. rr->length = 0;
  904. return 0;
  905. }
  906. if (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC) {
  907. /* 'Change Cipher Spec' is just a single byte, so we know exactly what the
  908. * record payload has to look like */
  909. if (rr->length != 1 || rr->off != 0 || rr->data[0] != SSL3_MT_CCS) {
  910. al = SSL_AD_ILLEGAL_PARAMETER;
  911. OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_BAD_CHANGE_CIPHER_SPEC);
  912. goto f_err;
  913. }
  914. /* Check we have a cipher to change to */
  915. if (s->s3->tmp.new_cipher == NULL) {
  916. al = SSL_AD_UNEXPECTED_MESSAGE;
  917. OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_CCS_RECEIVED_EARLY);
  918. goto f_err;
  919. }
  920. if (!(s->s3->flags & SSL3_FLAGS_EXPECT_CCS)) {
  921. al = SSL_AD_UNEXPECTED_MESSAGE;
  922. OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_CCS_RECEIVED_EARLY);
  923. goto f_err;
  924. }
  925. s->s3->flags &= ~SSL3_FLAGS_EXPECT_CCS;
  926. rr->length = 0;
  927. if (s->msg_callback) {
  928. s->msg_callback(0, s->version, SSL3_RT_CHANGE_CIPHER_SPEC, rr->data, 1, s,
  929. s->msg_callback_arg);
  930. }
  931. s->s3->change_cipher_spec = 1;
  932. if (!ssl3_do_change_cipher_spec(s)) {
  933. goto err;
  934. } else {
  935. goto start;
  936. }
  937. }
  938. /* Unexpected handshake message (Client Hello, or protocol violation) */
  939. if (s->s3->handshake_fragment_len >= 4 && !s->in_handshake) {
  940. if ((s->state & SSL_ST_MASK) == SSL_ST_OK) {
  941. s->state = s->server ? SSL_ST_ACCEPT : SSL_ST_CONNECT;
  942. s->renegotiate = 1;
  943. s->new_session = 1;
  944. }
  945. i = s->handshake_func(s);
  946. if (i < 0) {
  947. return i;
  948. }
  949. if (i == 0) {
  950. OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_SSL_HANDSHAKE_FAILURE);
  951. return -1;
  952. }
  953. goto start;
  954. }
  955. /* We already handled these. */
  956. assert(rr->type != SSL3_RT_CHANGE_CIPHER_SPEC && rr->type != SSL3_RT_ALERT &&
  957. rr->type != SSL3_RT_HANDSHAKE);
  958. al = SSL_AD_UNEXPECTED_MESSAGE;
  959. OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_UNEXPECTED_RECORD);
  960. f_err:
  961. ssl3_send_alert(s, SSL3_AL_FATAL, al);
  962. err:
  963. return -1;
  964. }
  965. int ssl3_do_change_cipher_spec(SSL *s) {
  966. int i;
  967. if (s->state & SSL_ST_ACCEPT) {
  968. i = SSL3_CHANGE_CIPHER_SERVER_READ;
  969. } else {
  970. i = SSL3_CHANGE_CIPHER_CLIENT_READ;
  971. }
  972. if (s->s3->tmp.key_block == NULL) {
  973. if (s->session == NULL || s->session->master_key_length == 0) {
  974. /* might happen if dtls1_read_bytes() calls this */
  975. OPENSSL_PUT_ERROR(SSL, ssl3_do_change_cipher_spec,
  976. SSL_R_CCS_RECEIVED_EARLY);
  977. return 0;
  978. }
  979. s->session->cipher = s->s3->tmp.new_cipher;
  980. if (!s->enc_method->setup_key_block(s)) {
  981. return 0;
  982. }
  983. }
  984. if (!s->enc_method->change_cipher_state(s, i)) {
  985. return 0;
  986. }
  987. return 1;
  988. }
  989. int ssl3_send_alert(SSL *s, int level, int desc) {
  990. /* Map tls/ssl alert value to correct one */
  991. desc = s->enc_method->alert_value(desc);
  992. if (s->version == SSL3_VERSION && desc == SSL_AD_PROTOCOL_VERSION) {
  993. /* SSL 3.0 does not have protocol_version alerts */
  994. desc = SSL_AD_HANDSHAKE_FAILURE;
  995. }
  996. if (desc < 0) {
  997. return -1;
  998. }
  999. /* If a fatal one, remove from cache */
  1000. if (level == 2 && s->session != NULL) {
  1001. SSL_CTX_remove_session(s->ctx, s->session);
  1002. }
  1003. s->s3->alert_dispatch = 1;
  1004. s->s3->send_alert[0] = level;
  1005. s->s3->send_alert[1] = desc;
  1006. if (s->s3->wbuf.left == 0) {
  1007. /* data is still being written out. */
  1008. return s->method->ssl_dispatch_alert(s);
  1009. }
  1010. /* else data is still being written out, we will get written some time in the
  1011. * future */
  1012. return -1;
  1013. }
  1014. int ssl3_dispatch_alert(SSL *s) {
  1015. int i, j;
  1016. void (*cb)(const SSL *ssl, int type, int val) = NULL;
  1017. s->s3->alert_dispatch = 0;
  1018. i = do_ssl3_write(s, SSL3_RT_ALERT, &s->s3->send_alert[0], 2, 0);
  1019. if (i <= 0) {
  1020. s->s3->alert_dispatch = 1;
  1021. } else {
  1022. /* Alert sent to BIO. If it is important, flush it now. If the message
  1023. * does not get sent due to non-blocking IO, we will not worry too much. */
  1024. if (s->s3->send_alert[0] == SSL3_AL_FATAL) {
  1025. BIO_flush(s->wbio);
  1026. }
  1027. if (s->msg_callback) {
  1028. s->msg_callback(1, s->version, SSL3_RT_ALERT, s->s3->send_alert, 2, s,
  1029. s->msg_callback_arg);
  1030. }
  1031. if (s->info_callback != NULL) {
  1032. cb = s->info_callback;
  1033. } else if (s->ctx->info_callback != NULL) {
  1034. cb = s->ctx->info_callback;
  1035. }
  1036. if (cb != NULL) {
  1037. j = (s->s3->send_alert[0] << 8) | s->s3->send_alert[1];
  1038. cb(s, SSL_CB_WRITE_ALERT, j);
  1039. }
  1040. }
  1041. return i;
  1042. }