Não pode escolher mais do que 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 
 
 

1436 linhas
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->s3->have_version)
  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))
  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->enc_method->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->enc_method->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. /* Some servers hang if initial ClientHello is larger than 256
  664. * bytes and record version number > TLS 1.0. */
  665. if (!s->s3->have_version && s->version > SSL3_VERSION)
  666. {
  667. *(p++) = TLS1_VERSION >> 8;
  668. *(p++) = TLS1_VERSION & 0xff;
  669. }
  670. else
  671. {
  672. *(p++) = s->version >> 8;
  673. *(p++) = s->version & 0xff;
  674. }
  675. /* field where we are to write out packet length */
  676. plen=p;
  677. p+=2;
  678. /* Explicit IV length, block ciphers appropriate version flag */
  679. if (s->enc_write_ctx && SSL_USE_EXPLICIT_IV(s))
  680. {
  681. int mode = EVP_CIPHER_CTX_mode(s->enc_write_ctx);
  682. if (mode == EVP_CIPH_CBC_MODE)
  683. {
  684. eivlen = EVP_CIPHER_CTX_iv_length(s->enc_write_ctx);
  685. if (eivlen <= 1)
  686. eivlen = 0;
  687. }
  688. else
  689. eivlen = 0;
  690. }
  691. else if (s->aead_write_ctx != NULL &&
  692. s->aead_write_ctx->variable_nonce_included_in_record)
  693. {
  694. eivlen = s->aead_write_ctx->variable_nonce_len;
  695. }
  696. else
  697. eivlen = 0;
  698. /* lets setup the record stuff. */
  699. wr->data=p + eivlen;
  700. wr->length=(int)(len - (fragment != 0));
  701. wr->input=(unsigned char *)buf + (fragment != 0);
  702. /* we now 'read' from wr->input, wr->length bytes into
  703. * wr->data */
  704. memcpy(wr->data,wr->input,wr->length);
  705. wr->input=wr->data;
  706. /* we should still have the output to wr->data and the input
  707. * from wr->input. Length should be wr->length.
  708. * wr->data still points in the wb->buf */
  709. if (mac_size != 0)
  710. {
  711. if (s->enc_method->mac(s,&(p[wr->length + eivlen]),1) < 0)
  712. goto err;
  713. wr->length+=mac_size;
  714. }
  715. wr->input=p;
  716. wr->data=p;
  717. if (eivlen)
  718. {
  719. /* if (RAND_pseudo_bytes(p, eivlen) <= 0)
  720. goto err; */
  721. wr->length += eivlen;
  722. }
  723. if (s->enc_method->enc(s, 1) < 1)
  724. goto err;
  725. /* record length after mac and block padding */
  726. s2n(wr->length,plen);
  727. if (s->msg_callback)
  728. s->msg_callback(1, 0, SSL3_RT_HEADER, plen - 5, 5, s, s->msg_callback_arg);
  729. /* we should now have
  730. * wr->data pointing to the encrypted data, which is
  731. * wr->length long */
  732. wr->type=type; /* not needed but helps for debugging */
  733. wr->length+=SSL3_RT_HEADER_LENGTH;
  734. if (is_fragment)
  735. {
  736. /* we are in a recursive call; just return the length, don't
  737. * write out anything. */
  738. return wr->length;
  739. }
  740. /* now let's set up wb */
  741. wb->left = prefix_len + wr->length;
  742. /* memorize arguments so that ssl3_write_pending can detect bad write retries later */
  743. s->s3->wpend_tot=len;
  744. s->s3->wpend_buf=buf;
  745. s->s3->wpend_type=type;
  746. s->s3->wpend_ret=len;
  747. /* we now just need to write the buffer */
  748. return ssl3_write_pending(s,type,buf,len);
  749. err:
  750. return -1;
  751. }
  752. /* if s->s3->wbuf.left != 0, we need to call this */
  753. int ssl3_write_pending(SSL *s, int type, const unsigned char *buf,
  754. unsigned int len)
  755. {
  756. int i;
  757. SSL3_BUFFER *wb=&(s->s3->wbuf);
  758. /* XXXX */
  759. if ((s->s3->wpend_tot > (int)len)
  760. || ((s->s3->wpend_buf != buf) &&
  761. !(s->mode & SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER))
  762. || (s->s3->wpend_type != type))
  763. {
  764. OPENSSL_PUT_ERROR(SSL, ssl3_write_pending, SSL_R_BAD_WRITE_RETRY);
  765. return(-1);
  766. }
  767. for (;;)
  768. {
  769. ERR_clear_system_error();
  770. if (s->wbio != NULL)
  771. {
  772. s->rwstate=SSL_WRITING;
  773. i=BIO_write(s->wbio,
  774. (char *)&(wb->buf[wb->offset]),
  775. (unsigned int)wb->left);
  776. }
  777. else
  778. {
  779. OPENSSL_PUT_ERROR(SSL, ssl3_write_pending, SSL_R_BIO_NOT_SET);
  780. i= -1;
  781. }
  782. if (i == wb->left)
  783. {
  784. wb->left=0;
  785. wb->offset+=i;
  786. if (s->mode & SSL_MODE_RELEASE_BUFFERS &&
  787. !SSL_IS_DTLS(s))
  788. ssl3_release_write_buffer(s);
  789. s->rwstate=SSL_NOTHING;
  790. return(s->s3->wpend_ret);
  791. }
  792. else if (i <= 0) {
  793. if (SSL_IS_DTLS(s)) {
  794. /* For DTLS, just drop it. That's kind of the whole
  795. point in using a datagram service */
  796. wb->left = 0;
  797. }
  798. return(i);
  799. }
  800. wb->offset+=i;
  801. wb->left-=i;
  802. }
  803. }
  804. /* ssl3_expect_change_cipher_spec informs the record layer that a
  805. * ChangeCipherSpec record is required at this point. If a Handshake record is
  806. * received before ChangeCipherSpec, the connection will fail. Moreover, if
  807. * there are unprocessed handshake bytes, the handshake will also fail and the
  808. * function returns zero. Otherwise, the function returns one. */
  809. int ssl3_expect_change_cipher_spec(SSL *s)
  810. {
  811. if (s->s3->handshake_fragment_len > 0 || s->s3->tmp.reuse_message)
  812. {
  813. OPENSSL_PUT_ERROR(SSL, ssl3_expect_change_cipher_spec, SSL_R_UNPROCESSED_HANDSHAKE_DATA);
  814. return 0;
  815. }
  816. s->s3->flags |= SSL3_FLAGS_EXPECT_CCS;
  817. return 1;
  818. }
  819. /* Return up to 'len' payload bytes received in 'type' records.
  820. * 'type' is one of the following:
  821. *
  822. * - SSL3_RT_HANDSHAKE (when ssl3_get_message calls us)
  823. * - SSL3_RT_APPLICATION_DATA (when ssl3_read calls us)
  824. * - 0 (during a shutdown, no data has to be returned)
  825. *
  826. * If we don't have stored data to work from, read a SSL/TLS record first
  827. * (possibly multiple records if we still don't have anything to return).
  828. *
  829. * This function must handle any surprises the peer may have for us, such as
  830. * Alert records (e.g. close_notify), ChangeCipherSpec records (not really
  831. * a surprise, but handled as if it were), or renegotiation requests.
  832. * Also if record payloads contain fragments too small to process, we store
  833. * them until there is enough for the respective protocol (the record protocol
  834. * may use arbitrary fragmentation and even interleaving):
  835. * Change cipher spec protocol
  836. * just 1 byte needed, no need for keeping anything stored
  837. * Alert protocol
  838. * 2 bytes needed (AlertLevel, AlertDescription)
  839. * Handshake protocol
  840. * 4 bytes needed (HandshakeType, uint24 length) -- we just have
  841. * to detect unexpected Client Hello and Hello Request messages
  842. * here, anything else is handled by higher layers
  843. * Application data protocol
  844. * none of our business
  845. */
  846. int ssl3_read_bytes(SSL *s, int type, unsigned char *buf, int len, int peek)
  847. {
  848. int al,i,j,ret;
  849. unsigned int n;
  850. SSL3_RECORD *rr;
  851. void (*cb)(const SSL *ssl,int type2,int val)=NULL;
  852. uint8_t alert_buffer[2];
  853. if (s->s3->rbuf.buf == NULL) /* Not initialized yet */
  854. if (!ssl3_setup_read_buffer(s))
  855. return(-1);
  856. if ((type && (type != SSL3_RT_APPLICATION_DATA) && (type != SSL3_RT_HANDSHAKE)) ||
  857. (peek && (type != SSL3_RT_APPLICATION_DATA)))
  858. {
  859. OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, ERR_R_INTERNAL_ERROR);
  860. return -1;
  861. }
  862. if ((type == SSL3_RT_HANDSHAKE) && (s->s3->handshake_fragment_len > 0))
  863. /* (partially) satisfy request from storage */
  864. {
  865. unsigned char *src = s->s3->handshake_fragment;
  866. unsigned char *dst = buf;
  867. unsigned int k;
  868. /* peek == 0 */
  869. n = 0;
  870. while ((len > 0) && (s->s3->handshake_fragment_len > 0))
  871. {
  872. *dst++ = *src++;
  873. len--; s->s3->handshake_fragment_len--;
  874. n++;
  875. }
  876. /* move any remaining fragment bytes: */
  877. for (k = 0; k < s->s3->handshake_fragment_len; k++)
  878. s->s3->handshake_fragment[k] = *src++;
  879. return n;
  880. }
  881. /* Now s->s3->handshake_fragment_len == 0 if type == SSL3_RT_HANDSHAKE. */
  882. if (!s->in_handshake && SSL_in_init(s))
  883. {
  884. /* type == SSL3_RT_APPLICATION_DATA */
  885. i=s->handshake_func(s);
  886. if (i < 0) return(i);
  887. if (i == 0)
  888. {
  889. OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_SSL_HANDSHAKE_FAILURE);
  890. return(-1);
  891. }
  892. }
  893. start:
  894. s->rwstate=SSL_NOTHING;
  895. /* s->s3->rrec.type - is the type of record
  896. * s->s3->rrec.data, - data
  897. * s->s3->rrec.off, - offset into 'data' for next read
  898. * s->s3->rrec.length, - number of bytes. */
  899. rr = &(s->s3->rrec);
  900. /* get new packet if necessary */
  901. if ((rr->length == 0) || (s->rstate == SSL_ST_READ_BODY))
  902. {
  903. ret=ssl3_get_record(s);
  904. if (ret <= 0) return(ret);
  905. }
  906. /* we now have a packet which can be read and processed */
  907. if (s->s3->change_cipher_spec /* set when we receive ChangeCipherSpec,
  908. * reset by ssl3_get_finished */
  909. && (rr->type != SSL3_RT_HANDSHAKE))
  910. {
  911. al=SSL_AD_UNEXPECTED_MESSAGE;
  912. OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_DATA_BETWEEN_CCS_AND_FINISHED);
  913. goto f_err;
  914. }
  915. /* If we are expecting a ChangeCipherSpec, it is illegal to receive a
  916. * Handshake record. */
  917. if (rr->type == SSL3_RT_HANDSHAKE && (s->s3->flags & SSL3_FLAGS_EXPECT_CCS))
  918. {
  919. al = SSL_AD_UNEXPECTED_MESSAGE;
  920. OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_HANDSHAKE_RECORD_BEFORE_CCS);
  921. goto f_err;
  922. }
  923. /* If the other end has shut down, throw anything we read away
  924. * (even in 'peek' mode) */
  925. if (s->shutdown & SSL_RECEIVED_SHUTDOWN)
  926. {
  927. rr->length=0;
  928. s->rwstate=SSL_NOTHING;
  929. return(0);
  930. }
  931. if (type == rr->type) /* SSL3_RT_APPLICATION_DATA or SSL3_RT_HANDSHAKE */
  932. {
  933. /* make sure that we are not getting application data when we
  934. * are doing a handshake for the first time */
  935. if (SSL_in_init(s) && (type == SSL3_RT_APPLICATION_DATA) &&
  936. (s->enc_read_ctx == NULL))
  937. {
  938. al=SSL_AD_UNEXPECTED_MESSAGE;
  939. OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_APP_DATA_IN_HANDSHAKE);
  940. goto f_err;
  941. }
  942. if (len <= 0) return(len);
  943. if ((unsigned int)len > rr->length)
  944. n = rr->length;
  945. else
  946. n = (unsigned int)len;
  947. memcpy(buf,&(rr->data[rr->off]),n);
  948. if (!peek)
  949. {
  950. rr->length-=n;
  951. rr->off+=n;
  952. if (rr->length == 0)
  953. {
  954. s->rstate=SSL_ST_READ_HEADER;
  955. rr->off=0;
  956. if (s->mode & SSL_MODE_RELEASE_BUFFERS && s->s3->rbuf.left == 0)
  957. ssl3_release_read_buffer(s);
  958. }
  959. }
  960. return(n);
  961. }
  962. /* If we get here, then type != rr->type; if we have a handshake
  963. * message, then it was unexpected (Hello Request or Client Hello). */
  964. /* In case of record types for which we have 'fragment' storage,
  965. * fill that so that we can process the data at a fixed place.
  966. */
  967. if (rr->type == SSL3_RT_HANDSHAKE)
  968. {
  969. const size_t size = sizeof(s->s3->handshake_fragment);
  970. const size_t avail = size - s->s3->handshake_fragment_len;
  971. const size_t todo = (rr->length < avail) ? rr->length : avail;
  972. memcpy(s->s3->handshake_fragment + s->s3->handshake_fragment_len,
  973. &rr->data[rr->off], todo);
  974. rr->off += todo;
  975. rr->length -= todo;
  976. s->s3->handshake_fragment_len += todo;
  977. if (s->s3->handshake_fragment_len < size)
  978. {
  979. goto start; /* fragment was too small */
  980. }
  981. }
  982. else if (rr->type == SSL3_RT_ALERT)
  983. {
  984. /* Note that this will still allow multiple alerts to
  985. * be processed in the same record */
  986. if (rr->length < sizeof(alert_buffer))
  987. {
  988. al = SSL_AD_DECODE_ERROR;
  989. OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_BAD_ALERT);
  990. goto f_err;
  991. }
  992. memcpy(alert_buffer, &rr->data[rr->off], sizeof(alert_buffer));
  993. rr->off += sizeof(alert_buffer);
  994. rr->length -= sizeof(alert_buffer);
  995. }
  996. /* s->s3->handshake_fragment_len == 4 iff rr->type == SSL3_RT_HANDSHAKE;
  997. * (Possibly rr is 'empty' now, i.e. rr->length may be 0.) */
  998. /* If we are a client, check for an incoming 'Hello Request': */
  999. if ((!s->server) &&
  1000. (s->s3->handshake_fragment_len >= 4) &&
  1001. (s->s3->handshake_fragment[0] == SSL3_MT_HELLO_REQUEST) &&
  1002. (s->session != NULL) && (s->session->cipher != NULL))
  1003. {
  1004. s->s3->handshake_fragment_len = 0;
  1005. if ((s->s3->handshake_fragment[1] != 0) ||
  1006. (s->s3->handshake_fragment[2] != 0) ||
  1007. (s->s3->handshake_fragment[3] != 0))
  1008. {
  1009. al=SSL_AD_DECODE_ERROR;
  1010. OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_BAD_HELLO_REQUEST);
  1011. goto f_err;
  1012. }
  1013. if (s->msg_callback)
  1014. s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE, s->s3->handshake_fragment, 4, s, s->msg_callback_arg);
  1015. if (SSL_is_init_finished(s) && !s->s3->renegotiate)
  1016. {
  1017. ssl3_renegotiate(s);
  1018. if (ssl3_renegotiate_check(s))
  1019. {
  1020. i=s->handshake_func(s);
  1021. if (i < 0) return(i);
  1022. if (i == 0)
  1023. {
  1024. OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_SSL_HANDSHAKE_FAILURE);
  1025. return(-1);
  1026. }
  1027. }
  1028. }
  1029. /* we either finished a handshake or ignored the request,
  1030. * now try again to obtain the (application) data we were asked for */
  1031. goto start;
  1032. }
  1033. if (rr->type == SSL3_RT_ALERT)
  1034. {
  1035. uint8_t alert_level = alert_buffer[0];
  1036. uint8_t alert_descr = alert_buffer[1];
  1037. if (s->msg_callback)
  1038. s->msg_callback(0, s->version, SSL3_RT_ALERT, alert_buffer, 2, s, s->msg_callback_arg);
  1039. if (s->info_callback != NULL)
  1040. cb=s->info_callback;
  1041. else if (s->ctx->info_callback != NULL)
  1042. cb=s->ctx->info_callback;
  1043. if (cb != NULL)
  1044. {
  1045. j = (alert_level << 8) | alert_descr;
  1046. cb(s, SSL_CB_READ_ALERT, j);
  1047. }
  1048. if (alert_level == 1) /* warning */
  1049. {
  1050. s->s3->warn_alert = alert_descr;
  1051. if (alert_descr == SSL_AD_CLOSE_NOTIFY)
  1052. {
  1053. s->shutdown |= SSL_RECEIVED_SHUTDOWN;
  1054. return(0);
  1055. }
  1056. /* This is a warning but we receive it if we requested
  1057. * renegotiation and the peer denied it. Terminate with
  1058. * a fatal alert because if application tried to
  1059. * renegotiatie it presumably had a good reason and
  1060. * expects it to succeed.
  1061. *
  1062. * In future we might have a renegotiation where we
  1063. * don't care if the peer refused it where we carry on.
  1064. */
  1065. else if (alert_descr == SSL_AD_NO_RENEGOTIATION)
  1066. {
  1067. al = SSL_AD_HANDSHAKE_FAILURE;
  1068. OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_NO_RENEGOTIATION);
  1069. goto f_err;
  1070. }
  1071. }
  1072. else if (alert_level == 2) /* fatal */
  1073. {
  1074. char tmp[16];
  1075. s->rwstate=SSL_NOTHING;
  1076. s->s3->fatal_alert = alert_descr;
  1077. OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_AD_REASON_OFFSET + alert_descr);
  1078. BIO_snprintf(tmp,sizeof tmp,"%d",alert_descr);
  1079. ERR_add_error_data(2,"SSL alert number ",tmp);
  1080. s->shutdown|=SSL_RECEIVED_SHUTDOWN;
  1081. SSL_CTX_remove_session(s->ctx,s->session);
  1082. return(0);
  1083. }
  1084. else
  1085. {
  1086. al=SSL_AD_ILLEGAL_PARAMETER;
  1087. OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_UNKNOWN_ALERT_TYPE);
  1088. goto f_err;
  1089. }
  1090. goto start;
  1091. }
  1092. if (s->shutdown & SSL_SENT_SHUTDOWN) /* but we have not received a shutdown */
  1093. {
  1094. s->rwstate=SSL_NOTHING;
  1095. rr->length=0;
  1096. return(0);
  1097. }
  1098. if (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC)
  1099. {
  1100. /* 'Change Cipher Spec' is just a single byte, so we know
  1101. * exactly what the record payload has to look like */
  1102. if ( (rr->length != 1) || (rr->off != 0) ||
  1103. (rr->data[0] != SSL3_MT_CCS))
  1104. {
  1105. al=SSL_AD_ILLEGAL_PARAMETER;
  1106. OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_BAD_CHANGE_CIPHER_SPEC);
  1107. goto f_err;
  1108. }
  1109. /* Check we have a cipher to change to */
  1110. if (s->s3->tmp.new_cipher == NULL)
  1111. {
  1112. al=SSL_AD_UNEXPECTED_MESSAGE;
  1113. OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_CCS_RECEIVED_EARLY);
  1114. goto f_err;
  1115. }
  1116. if (!(s->s3->flags & SSL3_FLAGS_EXPECT_CCS))
  1117. {
  1118. al=SSL_AD_UNEXPECTED_MESSAGE;
  1119. OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_CCS_RECEIVED_EARLY);
  1120. goto f_err;
  1121. }
  1122. s->s3->flags &= ~SSL3_FLAGS_EXPECT_CCS;
  1123. rr->length=0;
  1124. if (s->msg_callback)
  1125. s->msg_callback(0, s->version, SSL3_RT_CHANGE_CIPHER_SPEC, rr->data, 1, s, s->msg_callback_arg);
  1126. s->s3->change_cipher_spec=1;
  1127. if (!ssl3_do_change_cipher_spec(s))
  1128. goto err;
  1129. else
  1130. goto start;
  1131. }
  1132. /* Unexpected handshake message (Client Hello, or protocol violation) */
  1133. if ((s->s3->handshake_fragment_len >= 4) && !s->in_handshake)
  1134. {
  1135. if ((s->state&SSL_ST_MASK) == SSL_ST_OK)
  1136. {
  1137. s->state = s->server ? SSL_ST_ACCEPT : SSL_ST_CONNECT;
  1138. s->renegotiate=1;
  1139. s->new_session=1;
  1140. }
  1141. i=s->handshake_func(s);
  1142. if (i < 0) return(i);
  1143. if (i == 0)
  1144. {
  1145. OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_SSL_HANDSHAKE_FAILURE);
  1146. return(-1);
  1147. }
  1148. goto start;
  1149. }
  1150. switch (rr->type)
  1151. {
  1152. default:
  1153. /* TLS up to v1.1 just ignores unknown message types:
  1154. * TLS v1.2 give an unexpected message alert.
  1155. */
  1156. if (s->version >= TLS1_VERSION && s->version <= TLS1_1_VERSION)
  1157. {
  1158. rr->length = 0;
  1159. goto start;
  1160. }
  1161. al=SSL_AD_UNEXPECTED_MESSAGE;
  1162. OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_UNEXPECTED_RECORD);
  1163. goto f_err;
  1164. case SSL3_RT_CHANGE_CIPHER_SPEC:
  1165. case SSL3_RT_ALERT:
  1166. case SSL3_RT_HANDSHAKE:
  1167. /* we already handled all of these, with the possible exception
  1168. * of SSL3_RT_HANDSHAKE when s->in_handshake is set, but that
  1169. * should not happen when type != rr->type */
  1170. al=SSL_AD_UNEXPECTED_MESSAGE;
  1171. OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, ERR_R_INTERNAL_ERROR);
  1172. goto f_err;
  1173. case SSL3_RT_APPLICATION_DATA:
  1174. /* At this point, we were expecting handshake data,
  1175. * but have application data. If the library was
  1176. * running inside ssl3_read() (i.e. in_read_app_data
  1177. * is set) and it makes sense to read application data
  1178. * at this point (session renegotiation not yet started),
  1179. * we will indulge it.
  1180. */
  1181. if (s->s3->in_read_app_data &&
  1182. (s->s3->total_renegotiations != 0) &&
  1183. ((
  1184. (s->state & SSL_ST_CONNECT) &&
  1185. (s->state >= SSL3_ST_CW_CLNT_HELLO_A) &&
  1186. (s->state <= SSL3_ST_CR_SRVR_HELLO_A)
  1187. ) || (
  1188. (s->state & SSL_ST_ACCEPT) &&
  1189. (s->state <= SSL3_ST_SW_HELLO_REQ_A) &&
  1190. (s->state >= SSL3_ST_SR_CLNT_HELLO_A)
  1191. )
  1192. ))
  1193. {
  1194. s->s3->in_read_app_data=2;
  1195. return(-1);
  1196. }
  1197. else
  1198. {
  1199. al=SSL_AD_UNEXPECTED_MESSAGE;
  1200. OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_UNEXPECTED_RECORD);
  1201. goto f_err;
  1202. }
  1203. }
  1204. /* not reached */
  1205. f_err:
  1206. ssl3_send_alert(s,SSL3_AL_FATAL,al);
  1207. err:
  1208. return(-1);
  1209. }
  1210. int ssl3_do_change_cipher_spec(SSL *s)
  1211. {
  1212. int i;
  1213. if (s->state & SSL_ST_ACCEPT)
  1214. i=SSL3_CHANGE_CIPHER_SERVER_READ;
  1215. else
  1216. i=SSL3_CHANGE_CIPHER_CLIENT_READ;
  1217. if (s->s3->tmp.key_block == NULL)
  1218. {
  1219. if (s->session == NULL || s->session->master_key_length == 0)
  1220. {
  1221. /* might happen if dtls1_read_bytes() calls this */
  1222. OPENSSL_PUT_ERROR(SSL, ssl3_do_change_cipher_spec, SSL_R_CCS_RECEIVED_EARLY);
  1223. return (0);
  1224. }
  1225. s->session->cipher=s->s3->tmp.new_cipher;
  1226. if (!s->enc_method->setup_key_block(s)) return(0);
  1227. }
  1228. if (!s->enc_method->change_cipher_state(s,i))
  1229. return(0);
  1230. return(1);
  1231. }
  1232. int ssl3_send_alert(SSL *s, int level, int desc)
  1233. {
  1234. /* Map tls/ssl alert value to correct one */
  1235. desc=s->enc_method->alert_value(desc);
  1236. if (s->version == SSL3_VERSION && desc == SSL_AD_PROTOCOL_VERSION)
  1237. desc = SSL_AD_HANDSHAKE_FAILURE; /* SSL 3.0 does not have protocol_version alerts */
  1238. if (desc < 0) return -1;
  1239. /* If a fatal one, remove from cache */
  1240. if ((level == 2) && (s->session != NULL))
  1241. SSL_CTX_remove_session(s->ctx,s->session);
  1242. s->s3->alert_dispatch=1;
  1243. s->s3->send_alert[0]=level;
  1244. s->s3->send_alert[1]=desc;
  1245. if (s->s3->wbuf.left == 0) /* data still being written out? */
  1246. return s->method->ssl_dispatch_alert(s);
  1247. /* else data is still being written out, we will get written
  1248. * some time in the future */
  1249. return -1;
  1250. }
  1251. int ssl3_dispatch_alert(SSL *s)
  1252. {
  1253. int i,j;
  1254. void (*cb)(const SSL *ssl,int type,int val)=NULL;
  1255. s->s3->alert_dispatch=0;
  1256. i = do_ssl3_write(s, SSL3_RT_ALERT, &s->s3->send_alert[0], 2, 0, 0);
  1257. if (i <= 0)
  1258. {
  1259. s->s3->alert_dispatch=1;
  1260. }
  1261. else
  1262. {
  1263. /* Alert sent to BIO. If it is important, flush it now.
  1264. * If the message does not get sent due to non-blocking IO,
  1265. * we will not worry too much. */
  1266. if (s->s3->send_alert[0] == SSL3_AL_FATAL)
  1267. (void)BIO_flush(s->wbio);
  1268. if (s->msg_callback)
  1269. s->msg_callback(1, s->version, SSL3_RT_ALERT, s->s3->send_alert, 2, s, s->msg_callback_arg);
  1270. if (s->info_callback != NULL)
  1271. cb=s->info_callback;
  1272. else if (s->ctx->info_callback != NULL)
  1273. cb=s->ctx->info_callback;
  1274. if (cb != NULL)
  1275. {
  1276. j=(s->s3->send_alert[0]<<8)|s->s3->send_alert[1];
  1277. cb(s,SSL_CB_WRITE_ALERT,j);
  1278. }
  1279. }
  1280. return(i);
  1281. }