Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.
 
 
 
 
 
 

1438 řádky
41 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 unsigned char *buf,
  119. unsigned int len, 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. {
  123. /* If extend == 0, obtain new n-byte packet; if extend == 1, increase
  124. * packet by another n bytes.
  125. * The packet will be in the sub-array of s->s3->rbuf.buf specified
  126. * by s->packet and s->packet_length.
  127. * (If s->read_ahead is set, 'max' bytes may be stored in rbuf
  128. * [plus s->packet_length bytes if extend == 1].)
  129. */
  130. int i,len,left;
  131. long align=0;
  132. unsigned char *pkt;
  133. SSL3_BUFFER *rb;
  134. if (n <= 0) return n;
  135. rb = &(s->s3->rbuf);
  136. if (rb->buf == NULL)
  137. if (!ssl3_setup_read_buffer(s))
  138. return -1;
  139. left = rb->left;
  140. #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0
  141. align = (long)rb->buf + SSL3_RT_HEADER_LENGTH;
  142. align = (-align)&(SSL3_ALIGN_PAYLOAD-1);
  143. #endif
  144. if (!extend)
  145. {
  146. /* start with empty packet ... */
  147. if (left == 0)
  148. rb->offset = align;
  149. else if (align != 0 && left >= SSL3_RT_HEADER_LENGTH)
  150. {
  151. /* check if next packet length is large
  152. * enough to justify payload alignment... */
  153. pkt = rb->buf + rb->offset;
  154. if (pkt[0] == SSL3_RT_APPLICATION_DATA
  155. && (pkt[3]<<8|pkt[4]) >= 128)
  156. {
  157. /* Note that even if packet is corrupted
  158. * and its length field is insane, we can
  159. * only be led to wrong decision about
  160. * whether memmove will occur or not.
  161. * Header values has no effect on memmove
  162. * arguments and therefore no buffer
  163. * overrun can be triggered. */
  164. memmove (rb->buf+align,pkt,left);
  165. rb->offset = align;
  166. }
  167. }
  168. s->packet = rb->buf + rb->offset;
  169. s->packet_length = 0;
  170. /* ... now we can act as if 'extend' was set */
  171. }
  172. /* For DTLS/UDP reads should not span multiple packets
  173. * because the read operation returns the whole packet
  174. * at once (as long as it fits into the buffer). */
  175. if (SSL_IS_DTLS(s))
  176. {
  177. if (left > 0 && n > left)
  178. n = left;
  179. }
  180. /* if there is enough in the buffer from a previous read, take some */
  181. if (left >= n)
  182. {
  183. s->packet_length+=n;
  184. rb->left=left-n;
  185. rb->offset+=n;
  186. return(n);
  187. }
  188. /* else we need to read more data */
  189. len = s->packet_length;
  190. pkt = rb->buf+align;
  191. /* Move any available bytes to front of buffer:
  192. * 'len' bytes already pointed to by 'packet',
  193. * 'left' extra ones at the end */
  194. if (s->packet != pkt) /* len > 0 */
  195. {
  196. memmove(pkt, s->packet, len+left);
  197. s->packet = pkt;
  198. rb->offset = len + align;
  199. }
  200. if (n > (int)(rb->len - rb->offset)) /* does not happen */
  201. {
  202. OPENSSL_PUT_ERROR(SSL, ssl3_read_n, ERR_R_INTERNAL_ERROR);
  203. return -1;
  204. }
  205. if (!s->read_ahead)
  206. /* ignore max parameter */
  207. max = n;
  208. else
  209. {
  210. if (max < n)
  211. max = n;
  212. if (max > (int)(rb->len - rb->offset))
  213. max = rb->len - rb->offset;
  214. }
  215. while (left < n)
  216. {
  217. /* Now we have len+left bytes at the front of s->s3->rbuf.buf
  218. * and need to read in more until we have len+n (up to
  219. * len+max if possible) */
  220. ERR_clear_system_error();
  221. if (s->rbio != NULL)
  222. {
  223. s->rwstate=SSL_READING;
  224. i=BIO_read(s->rbio,pkt+len+left, max-left);
  225. }
  226. else
  227. {
  228. OPENSSL_PUT_ERROR(SSL, ssl3_read_n, SSL_R_READ_BIO_NOT_SET);
  229. i = -1;
  230. }
  231. if (i <= 0)
  232. {
  233. rb->left = left;
  234. if (s->mode & SSL_MODE_RELEASE_BUFFERS &&
  235. !SSL_IS_DTLS(s))
  236. if (len+left == 0)
  237. ssl3_release_read_buffer(s);
  238. return(i);
  239. }
  240. left+=i;
  241. /* reads should *never* span multiple packets for DTLS because
  242. * the underlying transport protocol is message oriented as opposed
  243. * to byte oriented as in the TLS case. */
  244. if (SSL_IS_DTLS(s))
  245. {
  246. if (n > left)
  247. n = left; /* makes the while condition false */
  248. }
  249. }
  250. /* done reading, now the book-keeping */
  251. rb->offset += n;
  252. rb->left = left - n;
  253. s->packet_length += n;
  254. s->rwstate=SSL_NOTHING;
  255. return(n);
  256. }
  257. /* MAX_EMPTY_RECORDS defines the number of consecutive, empty records that will
  258. * be processed per call to ssl3_get_record. Without this limit an attacker
  259. * could send empty records at a faster rate than we can process and cause
  260. * ssl3_get_record to loop forever. */
  261. #define MAX_EMPTY_RECORDS 32
  262. /* Call this to get a new input record.
  263. * It will return <= 0 if more data is needed, normally due to an error
  264. * or non-blocking IO.
  265. * When it finishes, one packet has been decoded and can be found in
  266. * ssl->s3->rrec.type - is the type of record
  267. * ssl->s3->rrec.data, - data
  268. * ssl->s3->rrec.length, - number of bytes
  269. */
  270. /* used only by ssl3_read_bytes */
  271. static int ssl3_get_record(SSL *s)
  272. {
  273. int ssl_major,ssl_minor,al;
  274. int enc_err,n,i,ret= -1;
  275. SSL3_RECORD *rr;
  276. SSL_SESSION *sess;
  277. unsigned char *p;
  278. unsigned char md[EVP_MAX_MD_SIZE];
  279. short version;
  280. unsigned mac_size, orig_len;
  281. size_t extra;
  282. unsigned empty_record_count = 0;
  283. rr= &(s->s3->rrec);
  284. sess=s->session;
  285. if (s->options & SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER)
  286. extra=SSL3_RT_MAX_EXTRA;
  287. else
  288. extra=0;
  289. if (extra && !s->s3->init_extra)
  290. {
  291. /* An application error: SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER
  292. * set after ssl3_setup_buffers() was done */
  293. OPENSSL_PUT_ERROR(SSL, ssl3_get_record, ERR_R_INTERNAL_ERROR);
  294. return -1;
  295. }
  296. again:
  297. /* check if we have the header */
  298. if ( (s->rstate != SSL_ST_READ_BODY) ||
  299. (s->packet_length < SSL3_RT_HEADER_LENGTH))
  300. {
  301. n=ssl3_read_n(s, SSL3_RT_HEADER_LENGTH, s->s3->rbuf.len, 0);
  302. if (n <= 0) return(n); /* error or non-blocking */
  303. s->rstate=SSL_ST_READ_BODY;
  304. p=s->packet;
  305. if (s->msg_callback)
  306. s->msg_callback(0, 0, SSL3_RT_HEADER, p, 5, s, s->msg_callback_arg);
  307. /* Pull apart the header into the SSL3_RECORD */
  308. rr->type= *(p++);
  309. ssl_major= *(p++);
  310. ssl_minor= *(p++);
  311. version=(ssl_major<<8)|ssl_minor;
  312. n2s(p,rr->length);
  313. #if 0
  314. fprintf(stderr, "Record type=%d, Length=%d\n", rr->type, rr->length);
  315. #endif
  316. /* Lets check version */
  317. if (!s->first_packet)
  318. {
  319. if (version != s->version)
  320. {
  321. OPENSSL_PUT_ERROR(SSL, ssl3_get_record, SSL_R_WRONG_VERSION_NUMBER);
  322. if ((s->version & 0xFF00) == (version & 0xFF00) && !s->enc_write_ctx && !s->write_hash)
  323. /* Send back error using their minor version number :-) */
  324. s->version = (unsigned short)version;
  325. al=SSL_AD_PROTOCOL_VERSION;
  326. goto f_err;
  327. }
  328. }
  329. if ((version>>8) != SSL3_VERSION_MAJOR)
  330. {
  331. OPENSSL_PUT_ERROR(SSL, ssl3_get_record, SSL_R_WRONG_VERSION_NUMBER);
  332. goto err;
  333. }
  334. if (rr->length > s->s3->rbuf.len - SSL3_RT_HEADER_LENGTH)
  335. {
  336. al=SSL_AD_RECORD_OVERFLOW;
  337. OPENSSL_PUT_ERROR(SSL, ssl3_get_record, SSL_R_PACKET_LENGTH_TOO_LONG);
  338. goto f_err;
  339. }
  340. /* now s->rstate == SSL_ST_READ_BODY */
  341. }
  342. /* s->rstate == SSL_ST_READ_BODY, get and decode the data */
  343. if (rr->length > s->packet_length-SSL3_RT_HEADER_LENGTH)
  344. {
  345. /* now s->packet_length == SSL3_RT_HEADER_LENGTH */
  346. i=rr->length;
  347. n=ssl3_read_n(s,i,i,1);
  348. if (n <= 0) return(n); /* error or non-blocking io */
  349. /* now n == rr->length,
  350. * and s->packet_length == SSL3_RT_HEADER_LENGTH + rr->length */
  351. }
  352. s->rstate=SSL_ST_READ_HEADER; /* set state for later operations */
  353. /* At this point, s->packet_length == SSL3_RT_HEADER_LNGTH + rr->length,
  354. * and we have that many bytes in s->packet
  355. */
  356. rr->input= &(s->packet[SSL3_RT_HEADER_LENGTH]);
  357. /* ok, we can now read from 's->packet' data into 'rr'
  358. * rr->input points at rr->length bytes, which
  359. * need to be copied into rr->data by either
  360. * the decryption or by the decompression
  361. * When the data is 'copied' into the rr->data buffer,
  362. * rr->input will be pointed at the new buffer */
  363. /* We now have - encrypted [ MAC [ compressed [ plain ] ] ]
  364. * rr->length bytes of encrypted compressed stuff. */
  365. /* check is not needed I believe */
  366. if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH+extra)
  367. {
  368. al=SSL_AD_RECORD_OVERFLOW;
  369. OPENSSL_PUT_ERROR(SSL, ssl3_get_record, SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
  370. goto f_err;
  371. }
  372. /* decrypt in place in 'rr->input' */
  373. rr->data=rr->input;
  374. enc_err = s->method->ssl3_enc->enc(s,0);
  375. /* enc_err is:
  376. * 0: (in non-constant time) if the record is publically invalid.
  377. * 1: if the padding is valid
  378. * -1: if the padding is invalid */
  379. if (enc_err == 0)
  380. {
  381. al=SSL_AD_DECRYPTION_FAILED;
  382. OPENSSL_PUT_ERROR(SSL, ssl3_get_record, SSL_R_BLOCK_CIPHER_PAD_IS_WRONG);
  383. goto f_err;
  384. }
  385. #ifdef TLS_DEBUG
  386. printf("dec %d\n",rr->length);
  387. { unsigned int z; for (z=0; z<rr->length; z++) printf("%02X%c",rr->data[z],((z+1)%16)?' ':'\n'); }
  388. printf("\n");
  389. #endif
  390. /* r->length is now the compressed data plus mac */
  391. if ((sess != NULL) &&
  392. (s->enc_read_ctx != NULL) &&
  393. (EVP_MD_CTX_md(s->read_hash) != NULL))
  394. {
  395. /* s->read_hash != NULL => mac_size != -1 */
  396. unsigned char *mac = NULL;
  397. unsigned char mac_tmp[EVP_MAX_MD_SIZE];
  398. mac_size=EVP_MD_CTX_size(s->read_hash);
  399. assert(mac_size <= EVP_MAX_MD_SIZE);
  400. /* kludge: *_cbc_remove_padding passes padding length in rr->type */
  401. orig_len = rr->length+((unsigned int)rr->type>>8);
  402. /* orig_len is the length of the record before any padding was
  403. * removed. This is public information, as is the MAC in use,
  404. * therefore we can safely process the record in a different
  405. * amount of time if it's too short to possibly contain a MAC.
  406. */
  407. if (orig_len < mac_size ||
  408. /* CBC records must have a padding length byte too. */
  409. (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
  410. orig_len < mac_size+1))
  411. {
  412. al=SSL_AD_DECODE_ERROR;
  413. OPENSSL_PUT_ERROR(SSL, ssl3_get_record, SSL_R_LENGTH_TOO_SHORT);
  414. goto f_err;
  415. }
  416. if (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE)
  417. {
  418. /* We update the length so that the TLS header bytes
  419. * can be constructed correctly but we need to extract
  420. * the MAC in constant time from within the record,
  421. * without leaking the contents of the padding bytes.
  422. * */
  423. mac = mac_tmp;
  424. ssl3_cbc_copy_mac(mac_tmp, rr, mac_size, orig_len);
  425. rr->length -= mac_size;
  426. }
  427. else
  428. {
  429. /* In this case there's no padding, so |orig_len|
  430. * equals |rec->length| and we checked that there's
  431. * enough bytes for |mac_size| above. */
  432. rr->length -= mac_size;
  433. mac = &rr->data[rr->length];
  434. }
  435. i=s->method->ssl3_enc->mac(s,md,0 /* not send */);
  436. if (i < 0 || mac == NULL || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0)
  437. enc_err = -1;
  438. if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH+extra+mac_size)
  439. enc_err = -1;
  440. }
  441. if (enc_err < 0)
  442. {
  443. /* A separate 'decryption_failed' alert was introduced with TLS 1.0,
  444. * SSL 3.0 only has 'bad_record_mac'. But unless a decryption
  445. * failure is directly visible from the ciphertext anyway,
  446. * we should not reveal which kind of error occured -- this
  447. * might become visible to an attacker (e.g. via a logfile) */
  448. al=SSL_AD_BAD_RECORD_MAC;
  449. OPENSSL_PUT_ERROR(SSL, ssl3_get_record, SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
  450. goto f_err;
  451. }
  452. if (rr->length > SSL3_RT_MAX_PLAIN_LENGTH+extra)
  453. {
  454. al=SSL_AD_RECORD_OVERFLOW;
  455. OPENSSL_PUT_ERROR(SSL, ssl3_get_record, SSL_R_DATA_LENGTH_TOO_LONG);
  456. goto f_err;
  457. }
  458. rr->off=0;
  459. /* So at this point the following is true
  460. * ssl->s3->rrec.type is the type of record
  461. * ssl->s3->rrec.length == number of bytes in record
  462. * ssl->s3->rrec.off == offset to first valid byte
  463. * ssl->s3->rrec.data == where to take bytes from, increment
  464. * after use :-).
  465. */
  466. /* we have pulled in a full packet so zero things */
  467. s->packet_length=0;
  468. /* just read a 0 length packet */
  469. if (rr->length == 0)
  470. {
  471. empty_record_count++;
  472. if (empty_record_count > MAX_EMPTY_RECORDS)
  473. {
  474. al=SSL_AD_UNEXPECTED_MESSAGE;
  475. OPENSSL_PUT_ERROR(SSL, ssl3_get_record, SSL_R_TOO_MANY_EMPTY_FRAGMENTS);
  476. goto f_err;
  477. }
  478. goto again;
  479. }
  480. #if 0
  481. fprintf(stderr, "Ultimate Record type=%d, Length=%d\n", rr->type, rr->length);
  482. #endif
  483. return(1);
  484. f_err:
  485. ssl3_send_alert(s,SSL3_AL_FATAL,al);
  486. err:
  487. return(ret);
  488. }
  489. /* Call this to write data in records of type 'type'
  490. * It will return <= 0 if not all data has been sent or non-blocking IO.
  491. */
  492. int ssl3_write_bytes(SSL *s, int type, const void *buf_, int len)
  493. {
  494. const unsigned char *buf=buf_;
  495. unsigned int tot,n,nw;
  496. int i;
  497. s->rwstate=SSL_NOTHING;
  498. assert(s->s3->wnum <= INT_MAX);
  499. tot=s->s3->wnum;
  500. s->s3->wnum=0;
  501. if (SSL_in_init(s) && !s->in_handshake)
  502. {
  503. i=s->handshake_func(s);
  504. if (i < 0) return(i);
  505. if (i == 0)
  506. {
  507. OPENSSL_PUT_ERROR(SSL, ssl3_write_bytes, SSL_R_SSL_HANDSHAKE_FAILURE);
  508. return -1;
  509. }
  510. }
  511. /* ensure that if we end up with a smaller value of data to write
  512. * out than the the original len from a write which didn't complete
  513. * for non-blocking I/O and also somehow ended up avoiding
  514. * the check for this in ssl3_write_pending/SSL_R_BAD_WRITE_RETRY as
  515. * it must never be possible to end up with (len-tot) as a large
  516. * number that will then promptly send beyond the end of the users
  517. * buffer ... so we trap and report the error in a way the user
  518. * will notice
  519. */
  520. if (len < 0 || (size_t)len < tot)
  521. {
  522. OPENSSL_PUT_ERROR(SSL, ssl3_write_bytes, SSL_R_BAD_LENGTH);
  523. return(-1);
  524. }
  525. n=(len-tot);
  526. for (;;)
  527. {
  528. /* max contains the maximum number of bytes that we can put
  529. * into a record. */
  530. unsigned max = s->max_send_fragment;
  531. /* fragment is true if do_ssl3_write should send the first byte
  532. * in its own record in order to randomise a CBC IV. */
  533. int fragment = 0;
  534. if (n > 1 &&
  535. s->s3->need_record_splitting &&
  536. type == SSL3_RT_APPLICATION_DATA &&
  537. !s->s3->record_split_done)
  538. {
  539. fragment = 1;
  540. /* record_split_done records that the splitting has
  541. * been done in case we hit an SSL_WANT_WRITE condition.
  542. * In that case, we don't need to do the split again. */
  543. s->s3->record_split_done = 1;
  544. }
  545. if (n > max)
  546. nw=max;
  547. else
  548. nw=n;
  549. i=do_ssl3_write(s, type, &(buf[tot]), nw, fragment, 0);
  550. if (i <= 0)
  551. {
  552. s->s3->wnum=tot;
  553. s->s3->record_split_done = 0;
  554. return i;
  555. }
  556. if ((i == (int)n) ||
  557. (type == SSL3_RT_APPLICATION_DATA &&
  558. (s->mode & SSL_MODE_ENABLE_PARTIAL_WRITE)))
  559. {
  560. /* next chunk of data should get another prepended,
  561. * one-byte fragment in ciphersuites with known-IV
  562. * weakness. */
  563. s->s3->record_split_done = 0;
  564. return tot+i;
  565. }
  566. n-=i;
  567. tot+=i;
  568. }
  569. }
  570. /* do_ssl3_write writes an SSL record of the given type. If |fragment| is 1
  571. * then it splits the record into a one byte record and a record with the rest
  572. * of the data in order to randomise a CBC IV. If |is_fragment| is true then
  573. * this call resulted from do_ssl3_write calling itself in order to create that
  574. * one byte fragment. */
  575. static int do_ssl3_write(SSL *s, int type, const unsigned char *buf,
  576. unsigned int len, char fragment, char is_fragment)
  577. {
  578. unsigned char *p,*plen;
  579. int i,mac_size;
  580. int prefix_len=0;
  581. int eivlen;
  582. long align=0;
  583. SSL3_RECORD *wr;
  584. SSL3_BUFFER *wb=&(s->s3->wbuf);
  585. SSL_SESSION *sess;
  586. /* first check if there is a SSL3_BUFFER still being written
  587. * out. This will happen with non blocking IO */
  588. if (wb->left != 0)
  589. return(ssl3_write_pending(s,type,buf,len));
  590. /* If we have an alert to send, lets send it */
  591. if (s->s3->alert_dispatch)
  592. {
  593. i=s->method->ssl_dispatch_alert(s);
  594. if (i <= 0)
  595. return(i);
  596. /* if it went, fall through and send more stuff */
  597. }
  598. if (wb->buf == NULL)
  599. if (!ssl3_setup_write_buffer(s))
  600. return -1;
  601. if (len == 0)
  602. return 0;
  603. wr= &(s->s3->wrec);
  604. sess=s->session;
  605. if ( (sess == NULL) ||
  606. (s->enc_write_ctx == NULL) ||
  607. (EVP_MD_CTX_md(s->write_hash) == NULL))
  608. {
  609. mac_size=0;
  610. }
  611. else
  612. {
  613. mac_size=EVP_MD_CTX_size(s->write_hash);
  614. if (mac_size < 0)
  615. goto err;
  616. }
  617. if (fragment)
  618. {
  619. /* countermeasure against known-IV weakness in CBC ciphersuites
  620. * (see http://www.openssl.org/~bodo/tls-cbc.txt) */
  621. prefix_len = do_ssl3_write(s, type, buf, 1 /* length */,
  622. 0 /* fragment */,
  623. 1 /* is_fragment */);
  624. if (prefix_len <= 0)
  625. goto err;
  626. if (prefix_len > (SSL3_RT_HEADER_LENGTH +
  627. SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD))
  628. {
  629. /* insufficient space */
  630. OPENSSL_PUT_ERROR(SSL, do_ssl3_write, ERR_R_INTERNAL_ERROR);
  631. goto err;
  632. }
  633. }
  634. if (is_fragment)
  635. {
  636. #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0
  637. /* The extra fragment would be couple of cipher blocks, and
  638. * that will be a multiple of SSL3_ALIGN_PAYLOAD. So, if we
  639. * want to align the real payload, we can just pretend that we
  640. * have two headers and a byte. */
  641. align = (long)wb->buf + 2*SSL3_RT_HEADER_LENGTH + 1;
  642. align = (-align)&(SSL3_ALIGN_PAYLOAD-1);
  643. #endif
  644. p = wb->buf + align;
  645. wb->offset = align;
  646. }
  647. else if (prefix_len)
  648. {
  649. p = wb->buf + wb->offset + prefix_len;
  650. }
  651. else
  652. {
  653. #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0
  654. align = (long)wb->buf + SSL3_RT_HEADER_LENGTH;
  655. align = (-align)&(SSL3_ALIGN_PAYLOAD-1);
  656. #endif
  657. p = wb->buf + align;
  658. wb->offset = align;
  659. }
  660. /* write the header */
  661. *(p++)=type&0xff;
  662. wr->type=type;
  663. *(p++)=(s->version>>8);
  664. /* Some servers hang if iniatial client hello is larger than 256
  665. * bytes and record version number > TLS 1.0
  666. */
  667. if (s->state == SSL3_ST_CW_CLNT_HELLO_B
  668. && !s->renegotiate
  669. && TLS1_get_version(s) > TLS1_VERSION)
  670. *(p++) = 0x1;
  671. else
  672. *(p++)=s->version&0xff;
  673. /* field where we are to write out packet length */
  674. plen=p;
  675. p+=2;
  676. /* Explicit IV length, block ciphers appropriate version flag */
  677. if (s->enc_write_ctx && SSL_USE_EXPLICIT_IV(s))
  678. {
  679. int mode = EVP_CIPHER_CTX_mode(s->enc_write_ctx);
  680. if (mode == EVP_CIPH_CBC_MODE)
  681. {
  682. eivlen = EVP_CIPHER_CTX_iv_length(s->enc_write_ctx);
  683. if (eivlen <= 1)
  684. eivlen = 0;
  685. }
  686. else
  687. eivlen = 0;
  688. }
  689. else if (s->aead_write_ctx != NULL &&
  690. s->aead_write_ctx->variable_nonce_included_in_record)
  691. {
  692. eivlen = s->aead_write_ctx->variable_nonce_len;
  693. }
  694. else
  695. eivlen = 0;
  696. /* lets setup the record stuff. */
  697. wr->data=p + eivlen;
  698. wr->length=(int)(len - (fragment != 0));
  699. wr->input=(unsigned char *)buf + (fragment != 0);
  700. /* we now 'read' from wr->input, wr->length bytes into
  701. * wr->data */
  702. memcpy(wr->data,wr->input,wr->length);
  703. wr->input=wr->data;
  704. /* we should still have the output to wr->data and the input
  705. * from wr->input. Length should be wr->length.
  706. * wr->data still points in the wb->buf */
  707. if (mac_size != 0)
  708. {
  709. if (s->method->ssl3_enc->mac(s,&(p[wr->length + eivlen]),1) < 0)
  710. goto err;
  711. wr->length+=mac_size;
  712. }
  713. wr->input=p;
  714. wr->data=p;
  715. if (eivlen)
  716. {
  717. /* if (RAND_pseudo_bytes(p, eivlen) <= 0)
  718. goto err; */
  719. wr->length += eivlen;
  720. }
  721. /* ssl3_enc can only have an error on read */
  722. s->method->ssl3_enc->enc(s,1);
  723. /* record length after mac and block padding */
  724. s2n(wr->length,plen);
  725. if (s->msg_callback)
  726. s->msg_callback(1, 0, SSL3_RT_HEADER, plen - 5, 5, s, s->msg_callback_arg);
  727. /* we should now have
  728. * wr->data pointing to the encrypted data, which is
  729. * wr->length long */
  730. wr->type=type; /* not needed but helps for debugging */
  731. wr->length+=SSL3_RT_HEADER_LENGTH;
  732. if (is_fragment)
  733. {
  734. /* we are in a recursive call; just return the length, don't
  735. * write out anything. */
  736. return wr->length;
  737. }
  738. /* now let's set up wb */
  739. wb->left = prefix_len + wr->length;
  740. /* memorize arguments so that ssl3_write_pending can detect bad write retries later */
  741. s->s3->wpend_tot=len;
  742. s->s3->wpend_buf=buf;
  743. s->s3->wpend_type=type;
  744. s->s3->wpend_ret=len;
  745. /* we now just need to write the buffer */
  746. return ssl3_write_pending(s,type,buf,len);
  747. err:
  748. return -1;
  749. }
  750. /* if s->s3->wbuf.left != 0, we need to call this */
  751. int ssl3_write_pending(SSL *s, int type, const unsigned char *buf,
  752. unsigned int len)
  753. {
  754. int i;
  755. SSL3_BUFFER *wb=&(s->s3->wbuf);
  756. /* XXXX */
  757. if ((s->s3->wpend_tot > (int)len)
  758. || ((s->s3->wpend_buf != buf) &&
  759. !(s->mode & SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER))
  760. || (s->s3->wpend_type != type))
  761. {
  762. OPENSSL_PUT_ERROR(SSL, ssl3_write_pending, SSL_R_BAD_WRITE_RETRY);
  763. return(-1);
  764. }
  765. for (;;)
  766. {
  767. ERR_clear_system_error();
  768. if (s->wbio != NULL)
  769. {
  770. s->rwstate=SSL_WRITING;
  771. i=BIO_write(s->wbio,
  772. (char *)&(wb->buf[wb->offset]),
  773. (unsigned int)wb->left);
  774. }
  775. else
  776. {
  777. OPENSSL_PUT_ERROR(SSL, ssl3_write_pending, SSL_R_BIO_NOT_SET);
  778. i= -1;
  779. }
  780. if (i == wb->left)
  781. {
  782. wb->left=0;
  783. wb->offset+=i;
  784. if (s->mode & SSL_MODE_RELEASE_BUFFERS &&
  785. !SSL_IS_DTLS(s))
  786. ssl3_release_write_buffer(s);
  787. s->rwstate=SSL_NOTHING;
  788. return(s->s3->wpend_ret);
  789. }
  790. else if (i <= 0) {
  791. if (SSL_IS_DTLS(s)) {
  792. /* For DTLS, just drop it. That's kind of the whole
  793. point in using a datagram service */
  794. wb->left = 0;
  795. }
  796. return(i);
  797. }
  798. wb->offset+=i;
  799. wb->left-=i;
  800. }
  801. }
  802. /* ssl3_expect_change_cipher_spec informs the record layer that a
  803. * ChangeCipherSpec record is required at this point. If a Handshake record is
  804. * received before ChangeCipherSpec, the connection will fail. Moreover, if
  805. * there are unprocessed handshake bytes, the handshake will also fail and the
  806. * function returns zero. Otherwise, the function returns one. */
  807. int ssl3_expect_change_cipher_spec(SSL *s)
  808. {
  809. if (s->s3->handshake_fragment_len > 0 || s->s3->tmp.reuse_message)
  810. {
  811. OPENSSL_PUT_ERROR(SSL, ssl3_expect_change_cipher_spec, SSL_R_UNPROCESSED_HANDSHAKE_DATA);
  812. return 0;
  813. }
  814. s->s3->flags |= SSL3_FLAGS_EXPECT_CCS;
  815. return 1;
  816. }
  817. /* Return up to 'len' payload bytes received in 'type' records.
  818. * 'type' is one of the following:
  819. *
  820. * - SSL3_RT_HANDSHAKE (when ssl3_get_message calls us)
  821. * - SSL3_RT_APPLICATION_DATA (when ssl3_read calls us)
  822. * - 0 (during a shutdown, no data has to be returned)
  823. *
  824. * If we don't have stored data to work from, read a SSL/TLS record first
  825. * (possibly multiple records if we still don't have anything to return).
  826. *
  827. * This function must handle any surprises the peer may have for us, such as
  828. * Alert records (e.g. close_notify), ChangeCipherSpec records (not really
  829. * a surprise, but handled as if it were), or renegotiation requests.
  830. * Also if record payloads contain fragments too small to process, we store
  831. * them until there is enough for the respective protocol (the record protocol
  832. * may use arbitrary fragmentation and even interleaving):
  833. * Change cipher spec protocol
  834. * just 1 byte needed, no need for keeping anything stored
  835. * Alert protocol
  836. * 2 bytes needed (AlertLevel, AlertDescription)
  837. * Handshake protocol
  838. * 4 bytes needed (HandshakeType, uint24 length) -- we just have
  839. * to detect unexpected Client Hello and Hello Request messages
  840. * here, anything else is handled by higher layers
  841. * Application data protocol
  842. * none of our business
  843. */
  844. int ssl3_read_bytes(SSL *s, int type, unsigned char *buf, int len, int peek)
  845. {
  846. int al,i,j,ret;
  847. unsigned int n;
  848. SSL3_RECORD *rr;
  849. void (*cb)(const SSL *ssl,int type2,int val)=NULL;
  850. uint8_t alert_buffer[2];
  851. if (s->s3->rbuf.buf == NULL) /* Not initialized yet */
  852. if (!ssl3_setup_read_buffer(s))
  853. return(-1);
  854. if ((type && (type != SSL3_RT_APPLICATION_DATA) && (type != SSL3_RT_HANDSHAKE)) ||
  855. (peek && (type != SSL3_RT_APPLICATION_DATA)))
  856. {
  857. OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, ERR_R_INTERNAL_ERROR);
  858. return -1;
  859. }
  860. if ((type == SSL3_RT_HANDSHAKE) && (s->s3->handshake_fragment_len > 0))
  861. /* (partially) satisfy request from storage */
  862. {
  863. unsigned char *src = s->s3->handshake_fragment;
  864. unsigned char *dst = buf;
  865. unsigned int k;
  866. /* peek == 0 */
  867. n = 0;
  868. while ((len > 0) && (s->s3->handshake_fragment_len > 0))
  869. {
  870. *dst++ = *src++;
  871. len--; s->s3->handshake_fragment_len--;
  872. n++;
  873. }
  874. /* move any remaining fragment bytes: */
  875. for (k = 0; k < s->s3->handshake_fragment_len; k++)
  876. s->s3->handshake_fragment[k] = *src++;
  877. return n;
  878. }
  879. /* Now s->s3->handshake_fragment_len == 0 if type == SSL3_RT_HANDSHAKE. */
  880. if (!s->in_handshake && SSL_in_init(s))
  881. {
  882. /* type == SSL3_RT_APPLICATION_DATA */
  883. i=s->handshake_func(s);
  884. if (i < 0) return(i);
  885. if (i == 0)
  886. {
  887. OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_SSL_HANDSHAKE_FAILURE);
  888. return(-1);
  889. }
  890. }
  891. start:
  892. s->rwstate=SSL_NOTHING;
  893. /* s->s3->rrec.type - is the type of record
  894. * s->s3->rrec.data, - data
  895. * s->s3->rrec.off, - offset into 'data' for next read
  896. * s->s3->rrec.length, - number of bytes. */
  897. rr = &(s->s3->rrec);
  898. /* get new packet if necessary */
  899. if ((rr->length == 0) || (s->rstate == SSL_ST_READ_BODY))
  900. {
  901. ret=ssl3_get_record(s);
  902. if (ret <= 0) return(ret);
  903. }
  904. /* we now have a packet which can be read and processed */
  905. if (s->s3->change_cipher_spec /* set when we receive ChangeCipherSpec,
  906. * reset by ssl3_get_finished */
  907. && (rr->type != SSL3_RT_HANDSHAKE))
  908. {
  909. al=SSL_AD_UNEXPECTED_MESSAGE;
  910. OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_DATA_BETWEEN_CCS_AND_FINISHED);
  911. goto f_err;
  912. }
  913. /* If we are expecting a ChangeCipherSpec, it is illegal to receive a
  914. * Handshake record. */
  915. if (rr->type == SSL3_RT_HANDSHAKE && (s->s3->flags & SSL3_FLAGS_EXPECT_CCS))
  916. {
  917. al = SSL_AD_UNEXPECTED_MESSAGE;
  918. OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_HANDSHAKE_RECORD_BEFORE_CCS);
  919. goto f_err;
  920. }
  921. /* If the other end has shut down, throw anything we read away
  922. * (even in 'peek' mode) */
  923. if (s->shutdown & SSL_RECEIVED_SHUTDOWN)
  924. {
  925. rr->length=0;
  926. s->rwstate=SSL_NOTHING;
  927. return(0);
  928. }
  929. if (type == rr->type) /* SSL3_RT_APPLICATION_DATA or SSL3_RT_HANDSHAKE */
  930. {
  931. /* make sure that we are not getting application data when we
  932. * are doing a handshake for the first time */
  933. if (SSL_in_init(s) && (type == SSL3_RT_APPLICATION_DATA) &&
  934. (s->enc_read_ctx == NULL))
  935. {
  936. al=SSL_AD_UNEXPECTED_MESSAGE;
  937. OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_APP_DATA_IN_HANDSHAKE);
  938. goto f_err;
  939. }
  940. if (len <= 0) return(len);
  941. if ((unsigned int)len > rr->length)
  942. n = rr->length;
  943. else
  944. n = (unsigned int)len;
  945. memcpy(buf,&(rr->data[rr->off]),n);
  946. if (!peek)
  947. {
  948. rr->length-=n;
  949. rr->off+=n;
  950. if (rr->length == 0)
  951. {
  952. s->rstate=SSL_ST_READ_HEADER;
  953. rr->off=0;
  954. if (s->mode & SSL_MODE_RELEASE_BUFFERS && s->s3->rbuf.left == 0)
  955. ssl3_release_read_buffer(s);
  956. }
  957. }
  958. return(n);
  959. }
  960. /* If we get here, then type != rr->type; if we have a handshake
  961. * message, then it was unexpected (Hello Request or Client Hello). */
  962. /* In case of record types for which we have 'fragment' storage,
  963. * fill that so that we can process the data at a fixed place.
  964. */
  965. if (rr->type == SSL3_RT_HANDSHAKE)
  966. {
  967. const size_t size = sizeof(s->s3->handshake_fragment);
  968. const size_t avail = size - s->s3->handshake_fragment_len;
  969. const size_t len = (rr->length < avail) ? rr->length : avail;
  970. memcpy(s->s3->handshake_fragment + s->s3->handshake_fragment_len,
  971. &rr->data[rr->off], len);
  972. rr->off += len;
  973. rr->length -= len;
  974. s->s3->handshake_fragment_len += len;
  975. if (s->s3->handshake_fragment_len < size)
  976. {
  977. goto start; /* fragment was too small */
  978. }
  979. }
  980. else if (rr->type == SSL3_RT_ALERT)
  981. {
  982. const size_t len = sizeof(alert_buffer);
  983. /* Note that this will still allow multiple alerts to
  984. * be processed in the same record */
  985. if (rr->length < sizeof(alert_buffer))
  986. {
  987. al = SSL_AD_DECODE_ERROR;
  988. OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_BAD_ALERT);
  989. goto f_err;
  990. }
  991. memcpy(alert_buffer, &rr->data[rr->off], len);
  992. rr->off += len;
  993. rr->length -= len;
  994. }
  995. /* s->s3->handshake_fragment_len == 4 iff rr->type == SSL3_RT_HANDSHAKE;
  996. * (Possibly rr is 'empty' now, i.e. rr->length may be 0.) */
  997. /* If we are a client, check for an incoming 'Hello Request': */
  998. if ((!s->server) &&
  999. (s->s3->handshake_fragment_len >= 4) &&
  1000. (s->s3->handshake_fragment[0] == SSL3_MT_HELLO_REQUEST) &&
  1001. (s->session != NULL) && (s->session->cipher != NULL))
  1002. {
  1003. s->s3->handshake_fragment_len = 0;
  1004. if ((s->s3->handshake_fragment[1] != 0) ||
  1005. (s->s3->handshake_fragment[2] != 0) ||
  1006. (s->s3->handshake_fragment[3] != 0))
  1007. {
  1008. al=SSL_AD_DECODE_ERROR;
  1009. OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_BAD_HELLO_REQUEST);
  1010. goto f_err;
  1011. }
  1012. if (s->msg_callback)
  1013. s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE, s->s3->handshake_fragment, 4, s, s->msg_callback_arg);
  1014. if (SSL_is_init_finished(s) &&
  1015. !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS) &&
  1016. !s->s3->renegotiate)
  1017. {
  1018. ssl3_renegotiate(s);
  1019. if (ssl3_renegotiate_check(s))
  1020. {
  1021. i=s->handshake_func(s);
  1022. if (i < 0) return(i);
  1023. if (i == 0)
  1024. {
  1025. OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_SSL_HANDSHAKE_FAILURE);
  1026. return(-1);
  1027. }
  1028. }
  1029. }
  1030. /* we either finished a handshake or ignored the request,
  1031. * now try again to obtain the (application) data we were asked for */
  1032. goto start;
  1033. }
  1034. if (rr->type == SSL3_RT_ALERT)
  1035. {
  1036. uint8_t alert_level = alert_buffer[0];
  1037. uint8_t alert_descr = alert_buffer[1];
  1038. if (s->msg_callback)
  1039. s->msg_callback(0, s->version, SSL3_RT_ALERT, alert_buffer, 2, s, s->msg_callback_arg);
  1040. if (s->info_callback != NULL)
  1041. cb=s->info_callback;
  1042. else if (s->ctx->info_callback != NULL)
  1043. cb=s->ctx->info_callback;
  1044. if (cb != NULL)
  1045. {
  1046. j = (alert_level << 8) | alert_descr;
  1047. cb(s, SSL_CB_READ_ALERT, j);
  1048. }
  1049. if (alert_level == 1) /* warning */
  1050. {
  1051. s->s3->warn_alert = alert_descr;
  1052. if (alert_descr == SSL_AD_CLOSE_NOTIFY)
  1053. {
  1054. s->shutdown |= SSL_RECEIVED_SHUTDOWN;
  1055. return(0);
  1056. }
  1057. /* This is a warning but we receive it if we requested
  1058. * renegotiation and the peer denied it. Terminate with
  1059. * a fatal alert because if application tried to
  1060. * renegotiatie it presumably had a good reason and
  1061. * expects it to succeed.
  1062. *
  1063. * In future we might have a renegotiation where we
  1064. * don't care if the peer refused it where we carry on.
  1065. */
  1066. else if (alert_descr == SSL_AD_NO_RENEGOTIATION)
  1067. {
  1068. al = SSL_AD_HANDSHAKE_FAILURE;
  1069. OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_NO_RENEGOTIATION);
  1070. goto f_err;
  1071. }
  1072. }
  1073. else if (alert_level == 2) /* fatal */
  1074. {
  1075. char tmp[16];
  1076. s->rwstate=SSL_NOTHING;
  1077. s->s3->fatal_alert = alert_descr;
  1078. OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_AD_REASON_OFFSET + alert_descr);
  1079. BIO_snprintf(tmp,sizeof tmp,"%d",alert_descr);
  1080. ERR_add_error_data(2,"SSL alert number ",tmp);
  1081. s->shutdown|=SSL_RECEIVED_SHUTDOWN;
  1082. SSL_CTX_remove_session(s->ctx,s->session);
  1083. return(0);
  1084. }
  1085. else
  1086. {
  1087. al=SSL_AD_ILLEGAL_PARAMETER;
  1088. OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_UNKNOWN_ALERT_TYPE);
  1089. goto f_err;
  1090. }
  1091. goto start;
  1092. }
  1093. if (s->shutdown & SSL_SENT_SHUTDOWN) /* but we have not received a shutdown */
  1094. {
  1095. s->rwstate=SSL_NOTHING;
  1096. rr->length=0;
  1097. return(0);
  1098. }
  1099. if (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC)
  1100. {
  1101. /* 'Change Cipher Spec' is just a single byte, so we know
  1102. * exactly what the record payload has to look like */
  1103. if ( (rr->length != 1) || (rr->off != 0) ||
  1104. (rr->data[0] != SSL3_MT_CCS))
  1105. {
  1106. al=SSL_AD_ILLEGAL_PARAMETER;
  1107. OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_BAD_CHANGE_CIPHER_SPEC);
  1108. goto f_err;
  1109. }
  1110. /* Check we have a cipher to change to */
  1111. if (s->s3->tmp.new_cipher == NULL)
  1112. {
  1113. al=SSL_AD_UNEXPECTED_MESSAGE;
  1114. OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_CCS_RECEIVED_EARLY);
  1115. goto f_err;
  1116. }
  1117. if (!(s->s3->flags & SSL3_FLAGS_EXPECT_CCS))
  1118. {
  1119. al=SSL_AD_UNEXPECTED_MESSAGE;
  1120. OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_CCS_RECEIVED_EARLY);
  1121. goto f_err;
  1122. }
  1123. s->s3->flags &= ~SSL3_FLAGS_EXPECT_CCS;
  1124. rr->length=0;
  1125. if (s->msg_callback)
  1126. s->msg_callback(0, s->version, SSL3_RT_CHANGE_CIPHER_SPEC, rr->data, 1, s, s->msg_callback_arg);
  1127. s->s3->change_cipher_spec=1;
  1128. if (!ssl3_do_change_cipher_spec(s))
  1129. goto err;
  1130. else
  1131. goto start;
  1132. }
  1133. /* Unexpected handshake message (Client Hello, or protocol violation) */
  1134. if ((s->s3->handshake_fragment_len >= 4) && !s->in_handshake)
  1135. {
  1136. if (((s->state&SSL_ST_MASK) == SSL_ST_OK) &&
  1137. !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS))
  1138. {
  1139. s->state = s->server ? SSL_ST_ACCEPT : SSL_ST_CONNECT;
  1140. s->renegotiate=1;
  1141. s->new_session=1;
  1142. }
  1143. i=s->handshake_func(s);
  1144. if (i < 0) return(i);
  1145. if (i == 0)
  1146. {
  1147. OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_SSL_HANDSHAKE_FAILURE);
  1148. return(-1);
  1149. }
  1150. goto start;
  1151. }
  1152. switch (rr->type)
  1153. {
  1154. default:
  1155. /* TLS up to v1.1 just ignores unknown message types:
  1156. * TLS v1.2 give an unexpected message alert.
  1157. */
  1158. if (s->version >= TLS1_VERSION && s->version <= TLS1_1_VERSION)
  1159. {
  1160. rr->length = 0;
  1161. goto start;
  1162. }
  1163. al=SSL_AD_UNEXPECTED_MESSAGE;
  1164. OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_UNEXPECTED_RECORD);
  1165. goto f_err;
  1166. case SSL3_RT_CHANGE_CIPHER_SPEC:
  1167. case SSL3_RT_ALERT:
  1168. case SSL3_RT_HANDSHAKE:
  1169. /* we already handled all of these, with the possible exception
  1170. * of SSL3_RT_HANDSHAKE when s->in_handshake is set, but that
  1171. * should not happen when type != rr->type */
  1172. al=SSL_AD_UNEXPECTED_MESSAGE;
  1173. OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, ERR_R_INTERNAL_ERROR);
  1174. goto f_err;
  1175. case SSL3_RT_APPLICATION_DATA:
  1176. /* At this point, we were expecting handshake data,
  1177. * but have application data. If the library was
  1178. * running inside ssl3_read() (i.e. in_read_app_data
  1179. * is set) and it makes sense to read application data
  1180. * at this point (session renegotiation not yet started),
  1181. * we will indulge it.
  1182. */
  1183. if (s->s3->in_read_app_data &&
  1184. (s->s3->total_renegotiations != 0) &&
  1185. ((
  1186. (s->state & SSL_ST_CONNECT) &&
  1187. (s->state >= SSL3_ST_CW_CLNT_HELLO_A) &&
  1188. (s->state <= SSL3_ST_CR_SRVR_HELLO_A)
  1189. ) || (
  1190. (s->state & SSL_ST_ACCEPT) &&
  1191. (s->state <= SSL3_ST_SW_HELLO_REQ_A) &&
  1192. (s->state >= SSL3_ST_SR_CLNT_HELLO_A)
  1193. )
  1194. ))
  1195. {
  1196. s->s3->in_read_app_data=2;
  1197. return(-1);
  1198. }
  1199. else
  1200. {
  1201. al=SSL_AD_UNEXPECTED_MESSAGE;
  1202. OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_UNEXPECTED_RECORD);
  1203. goto f_err;
  1204. }
  1205. }
  1206. /* not reached */
  1207. f_err:
  1208. ssl3_send_alert(s,SSL3_AL_FATAL,al);
  1209. err:
  1210. return(-1);
  1211. }
  1212. int ssl3_do_change_cipher_spec(SSL *s)
  1213. {
  1214. int i;
  1215. if (s->state & SSL_ST_ACCEPT)
  1216. i=SSL3_CHANGE_CIPHER_SERVER_READ;
  1217. else
  1218. i=SSL3_CHANGE_CIPHER_CLIENT_READ;
  1219. if (s->s3->tmp.key_block == NULL)
  1220. {
  1221. if (s->session == NULL || s->session->master_key_length == 0)
  1222. {
  1223. /* might happen if dtls1_read_bytes() calls this */
  1224. OPENSSL_PUT_ERROR(SSL, ssl3_do_change_cipher_spec, SSL_R_CCS_RECEIVED_EARLY);
  1225. return (0);
  1226. }
  1227. s->session->cipher=s->s3->tmp.new_cipher;
  1228. if (!s->method->ssl3_enc->setup_key_block(s)) return(0);
  1229. }
  1230. if (!s->method->ssl3_enc->change_cipher_state(s,i))
  1231. return(0);
  1232. return(1);
  1233. }
  1234. int ssl3_send_alert(SSL *s, int level, int desc)
  1235. {
  1236. /* Map tls/ssl alert value to correct one */
  1237. desc=s->method->ssl3_enc->alert_value(desc);
  1238. if (s->version == SSL3_VERSION && desc == SSL_AD_PROTOCOL_VERSION)
  1239. desc = SSL_AD_HANDSHAKE_FAILURE; /* SSL 3.0 does not have protocol_version alerts */
  1240. if (desc < 0) return -1;
  1241. /* If a fatal one, remove from cache */
  1242. if ((level == 2) && (s->session != NULL))
  1243. SSL_CTX_remove_session(s->ctx,s->session);
  1244. s->s3->alert_dispatch=1;
  1245. s->s3->send_alert[0]=level;
  1246. s->s3->send_alert[1]=desc;
  1247. if (s->s3->wbuf.left == 0) /* data still being written out? */
  1248. return s->method->ssl_dispatch_alert(s);
  1249. /* else data is still being written out, we will get written
  1250. * some time in the future */
  1251. return -1;
  1252. }
  1253. int ssl3_dispatch_alert(SSL *s)
  1254. {
  1255. int i,j;
  1256. void (*cb)(const SSL *ssl,int type,int val)=NULL;
  1257. s->s3->alert_dispatch=0;
  1258. i = do_ssl3_write(s, SSL3_RT_ALERT, &s->s3->send_alert[0], 2, 0, 0);
  1259. if (i <= 0)
  1260. {
  1261. s->s3->alert_dispatch=1;
  1262. }
  1263. else
  1264. {
  1265. /* Alert sent to BIO. If it is important, flush it now.
  1266. * If the message does not get sent due to non-blocking IO,
  1267. * we will not worry too much. */
  1268. if (s->s3->send_alert[0] == SSL3_AL_FATAL)
  1269. (void)BIO_flush(s->wbio);
  1270. if (s->msg_callback)
  1271. s->msg_callback(1, s->version, SSL3_RT_ALERT, s->s3->send_alert, 2, s, s->msg_callback_arg);
  1272. if (s->info_callback != NULL)
  1273. cb=s->info_callback;
  1274. else if (s->ctx->info_callback != NULL)
  1275. cb=s->ctx->info_callback;
  1276. if (cb != NULL)
  1277. {
  1278. j=(s->s3->send_alert[0]<<8)|s->s3->send_alert[1];
  1279. cb(s,SSL_CB_WRITE_ALERT,j);
  1280. }
  1281. }
  1282. return(i);
  1283. }