You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

1516 lines
43 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: SLS_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 < 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. /* The first byte will be in its own record, so we
  541. * can write an extra byte. */
  542. max++;
  543. /* record_split_done records that the splitting has
  544. * been done in case we hit an SSL_WANT_WRITE condition.
  545. * In that case, we don't need to do the split again. */
  546. s->s3->record_split_done = 1;
  547. }
  548. if (n > max)
  549. nw=max;
  550. else
  551. nw=n;
  552. i=do_ssl3_write(s, type, &(buf[tot]), nw, fragment, 0);
  553. if (i <= 0)
  554. {
  555. s->s3->wnum=tot;
  556. return i;
  557. }
  558. if ((i == (int)n) ||
  559. (type == SSL3_RT_APPLICATION_DATA &&
  560. (s->mode & SSL_MODE_ENABLE_PARTIAL_WRITE)))
  561. {
  562. /* next chunk of data should get another prepended,
  563. * one-byte fragment in ciphersuites with known-IV
  564. * weakness. */
  565. s->s3->record_split_done = 0;
  566. return tot+i;
  567. }
  568. n-=i;
  569. tot+=i;
  570. }
  571. }
  572. /* do_ssl3_write writes an SSL record of the given type. If |fragment| is 1
  573. * then it splits the record into a one byte record and a record with the rest
  574. * of the data in order to randomise a CBC IV. If |is_fragment| is true then
  575. * this call resulted from do_ssl3_write calling itself in order to create that
  576. * one byte fragment. */
  577. static int do_ssl3_write(SSL *s, int type, const unsigned char *buf,
  578. unsigned int len, char fragment, char is_fragment)
  579. {
  580. unsigned char *p,*plen;
  581. int i,mac_size;
  582. int prefix_len=0;
  583. int eivlen;
  584. long align=0;
  585. SSL3_RECORD *wr;
  586. SSL3_BUFFER *wb=&(s->s3->wbuf);
  587. SSL_SESSION *sess;
  588. /* first check if there is a SSL3_BUFFER still being written
  589. * out. This will happen with non blocking IO */
  590. if (wb->left != 0)
  591. return(ssl3_write_pending(s,type,buf,len));
  592. /* If we have an alert to send, lets send it */
  593. if (s->s3->alert_dispatch)
  594. {
  595. i=s->method->ssl_dispatch_alert(s);
  596. if (i <= 0)
  597. return(i);
  598. /* if it went, fall through and send more stuff */
  599. }
  600. if (wb->buf == NULL)
  601. if (!ssl3_setup_write_buffer(s))
  602. return -1;
  603. if (len == 0)
  604. return 0;
  605. wr= &(s->s3->wrec);
  606. sess=s->session;
  607. if ( (sess == NULL) ||
  608. (s->enc_write_ctx == NULL) ||
  609. (EVP_MD_CTX_md(s->write_hash) == NULL))
  610. {
  611. mac_size=0;
  612. }
  613. else
  614. {
  615. mac_size=EVP_MD_CTX_size(s->write_hash);
  616. if (mac_size < 0)
  617. goto err;
  618. }
  619. if (fragment)
  620. {
  621. /* countermeasure against known-IV weakness in CBC ciphersuites
  622. * (see http://www.openssl.org/~bodo/tls-cbc.txt) */
  623. prefix_len = do_ssl3_write(s, type, buf, 1 /* length */,
  624. 0 /* fragment */,
  625. 1 /* is_fragment */);
  626. if (prefix_len <= 0)
  627. goto err;
  628. if (prefix_len > (SSL3_RT_HEADER_LENGTH +
  629. SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD))
  630. {
  631. /* insufficient space */
  632. OPENSSL_PUT_ERROR(SSL, do_ssl3_write, ERR_R_INTERNAL_ERROR);
  633. goto err;
  634. }
  635. }
  636. if (is_fragment)
  637. {
  638. #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0
  639. /* The extra fragment would be couple of cipher blocks, and
  640. * that will be a multiple of SSL3_ALIGN_PAYLOAD. So, if we
  641. * want to align the real payload, we can just pretend that we
  642. * have two headers and a byte. */
  643. align = (long)wb->buf + 2*SSL3_RT_HEADER_LENGTH + 1;
  644. align = (-align)&(SSL3_ALIGN_PAYLOAD-1);
  645. #endif
  646. p = wb->buf + align;
  647. wb->offset = align;
  648. }
  649. else if (prefix_len)
  650. {
  651. p = wb->buf + wb->offset + prefix_len;
  652. }
  653. else
  654. {
  655. #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0
  656. align = (long)wb->buf + SSL3_RT_HEADER_LENGTH;
  657. align = (-align)&(SSL3_ALIGN_PAYLOAD-1);
  658. #endif
  659. p = wb->buf + align;
  660. wb->offset = align;
  661. }
  662. /* write the header */
  663. *(p++)=type&0xff;
  664. wr->type=type;
  665. *(p++)=(s->version>>8);
  666. /* Some servers hang if iniatial client hello is larger than 256
  667. * bytes and record version number > TLS 1.0
  668. */
  669. if (s->state == SSL3_ST_CW_CLNT_HELLO_B
  670. && !s->renegotiate
  671. && TLS1_get_version(s) > TLS1_VERSION)
  672. *(p++) = 0x1;
  673. else
  674. *(p++)=s->version&0xff;
  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. /* Need explicit part of IV for GCM mode */
  689. else if (mode == EVP_CIPH_GCM_MODE)
  690. eivlen = EVP_GCM_TLS_EXPLICIT_IV_LEN;
  691. else
  692. eivlen = 0;
  693. }
  694. else if (s->aead_write_ctx != NULL &&
  695. s->aead_write_ctx->variable_nonce_included_in_record)
  696. {
  697. eivlen = s->aead_write_ctx->variable_nonce_len;
  698. }
  699. else
  700. eivlen = 0;
  701. /* lets setup the record stuff. */
  702. wr->data=p + eivlen;
  703. wr->length=(int)(len - (fragment != 0));
  704. wr->input=(unsigned char *)buf + (fragment != 0);
  705. /* we now 'read' from wr->input, wr->length bytes into
  706. * wr->data */
  707. memcpy(wr->data,wr->input,wr->length);
  708. wr->input=wr->data;
  709. /* we should still have the output to wr->data and the input
  710. * from wr->input. Length should be wr->length.
  711. * wr->data still points in the wb->buf */
  712. if (mac_size != 0)
  713. {
  714. if (s->method->ssl3_enc->mac(s,&(p[wr->length + eivlen]),1) < 0)
  715. goto err;
  716. wr->length+=mac_size;
  717. }
  718. wr->input=p;
  719. wr->data=p;
  720. if (eivlen)
  721. {
  722. /* if (RAND_pseudo_bytes(p, eivlen) <= 0)
  723. goto err; */
  724. wr->length += eivlen;
  725. }
  726. /* ssl3_enc can only have an error on read */
  727. s->method->ssl3_enc->enc(s,1);
  728. /* record length after mac and block padding */
  729. s2n(wr->length,plen);
  730. if (s->msg_callback)
  731. s->msg_callback(1, 0, SSL3_RT_HEADER, plen - 5, 5, s, s->msg_callback_arg);
  732. /* we should now have
  733. * wr->data pointing to the encrypted data, which is
  734. * wr->length long */
  735. wr->type=type; /* not needed but helps for debugging */
  736. wr->length+=SSL3_RT_HEADER_LENGTH;
  737. if (is_fragment)
  738. {
  739. /* we are in a recursive call; just return the length, don't
  740. * write out anything. */
  741. return wr->length;
  742. }
  743. /* now let's set up wb */
  744. wb->left = prefix_len + wr->length;
  745. /* memorize arguments so that ssl3_write_pending can detect bad write retries later */
  746. s->s3->wpend_tot=len;
  747. s->s3->wpend_buf=buf;
  748. s->s3->wpend_type=type;
  749. s->s3->wpend_ret=len;
  750. /* we now just need to write the buffer */
  751. return ssl3_write_pending(s,type,buf,len);
  752. err:
  753. return -1;
  754. }
  755. /* if s->s3->wbuf.left != 0, we need to call this */
  756. int ssl3_write_pending(SSL *s, int type, const unsigned char *buf,
  757. unsigned int len)
  758. {
  759. int i;
  760. SSL3_BUFFER *wb=&(s->s3->wbuf);
  761. /* XXXX */
  762. if ((s->s3->wpend_tot > (int)len)
  763. || ((s->s3->wpend_buf != buf) &&
  764. !(s->mode & SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER))
  765. || (s->s3->wpend_type != type))
  766. {
  767. OPENSSL_PUT_ERROR(SSL, ssl3_write_pending, SSL_R_BAD_WRITE_RETRY);
  768. return(-1);
  769. }
  770. for (;;)
  771. {
  772. ERR_clear_system_error();
  773. if (s->wbio != NULL)
  774. {
  775. s->rwstate=SSL_WRITING;
  776. i=BIO_write(s->wbio,
  777. (char *)&(wb->buf[wb->offset]),
  778. (unsigned int)wb->left);
  779. }
  780. else
  781. {
  782. OPENSSL_PUT_ERROR(SSL, ssl3_write_pending, SSL_R_BIO_NOT_SET);
  783. i= -1;
  784. }
  785. if (i == wb->left)
  786. {
  787. wb->left=0;
  788. wb->offset+=i;
  789. if (s->mode & SSL_MODE_RELEASE_BUFFERS &&
  790. !SSL_IS_DTLS(s))
  791. ssl3_release_write_buffer(s);
  792. s->rwstate=SSL_NOTHING;
  793. return(s->s3->wpend_ret);
  794. }
  795. else if (i <= 0) {
  796. if (s->version == DTLS1_VERSION ||
  797. s->version == DTLS1_BAD_VER) {
  798. /* For DTLS, just drop it. That's kind of the whole
  799. point in using a datagram service */
  800. wb->left = 0;
  801. }
  802. return(i);
  803. }
  804. wb->offset+=i;
  805. wb->left-=i;
  806. }
  807. }
  808. /* Return up to 'len' payload bytes received in 'type' records.
  809. * 'type' is one of the following:
  810. *
  811. * - SSL3_RT_HANDSHAKE (when ssl3_get_message calls us)
  812. * - SSL3_RT_APPLICATION_DATA (when ssl3_read calls us)
  813. * - 0 (during a shutdown, no data has to be returned)
  814. *
  815. * If we don't have stored data to work from, read a SSL/TLS record first
  816. * (possibly multiple records if we still don't have anything to return).
  817. *
  818. * This function must handle any surprises the peer may have for us, such as
  819. * Alert records (e.g. close_notify), ChangeCipherSpec records (not really
  820. * a surprise, but handled as if it were), or renegotiation requests.
  821. * Also if record payloads contain fragments too small to process, we store
  822. * them until there is enough for the respective protocol (the record protocol
  823. * may use arbitrary fragmentation and even interleaving):
  824. * Change cipher spec protocol
  825. * just 1 byte needed, no need for keeping anything stored
  826. * Alert protocol
  827. * 2 bytes needed (AlertLevel, AlertDescription)
  828. * Handshake protocol
  829. * 4 bytes needed (HandshakeType, uint24 length) -- we just have
  830. * to detect unexpected Client Hello and Hello Request messages
  831. * here, anything else is handled by higher layers
  832. * Application data protocol
  833. * none of our business
  834. */
  835. int ssl3_read_bytes(SSL *s, int type, unsigned char *buf, int len, int peek)
  836. {
  837. int al,i,j,ret;
  838. unsigned int n;
  839. SSL3_RECORD *rr;
  840. void (*cb)(const SSL *ssl,int type2,int val)=NULL;
  841. if (s->s3->rbuf.buf == NULL) /* Not initialized yet */
  842. if (!ssl3_setup_read_buffer(s))
  843. return(-1);
  844. if ((type && (type != SSL3_RT_APPLICATION_DATA) && (type != SSL3_RT_HANDSHAKE) && type) ||
  845. (peek && (type != SSL3_RT_APPLICATION_DATA)))
  846. {
  847. OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, ERR_R_INTERNAL_ERROR);
  848. return -1;
  849. }
  850. if ((type == SSL3_RT_HANDSHAKE) && (s->s3->handshake_fragment_len > 0))
  851. /* (partially) satisfy request from storage */
  852. {
  853. unsigned char *src = s->s3->handshake_fragment;
  854. unsigned char *dst = buf;
  855. unsigned int k;
  856. /* peek == 0 */
  857. n = 0;
  858. while ((len > 0) && (s->s3->handshake_fragment_len > 0))
  859. {
  860. *dst++ = *src++;
  861. len--; s->s3->handshake_fragment_len--;
  862. n++;
  863. }
  864. /* move any remaining fragment bytes: */
  865. for (k = 0; k < s->s3->handshake_fragment_len; k++)
  866. s->s3->handshake_fragment[k] = *src++;
  867. return n;
  868. }
  869. /* Now s->s3->handshake_fragment_len == 0 if type == SSL3_RT_HANDSHAKE. */
  870. if (!s->in_handshake && SSL_in_init(s))
  871. {
  872. /* type == SSL3_RT_APPLICATION_DATA */
  873. i=s->handshake_func(s);
  874. if (i < 0) return(i);
  875. if (i == 0)
  876. {
  877. OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_SSL_HANDSHAKE_FAILURE);
  878. return(-1);
  879. }
  880. }
  881. start:
  882. s->rwstate=SSL_NOTHING;
  883. /* s->s3->rrec.type - is the type of record
  884. * s->s3->rrec.data, - data
  885. * s->s3->rrec.off, - offset into 'data' for next read
  886. * s->s3->rrec.length, - number of bytes. */
  887. rr = &(s->s3->rrec);
  888. /* get new packet if necessary */
  889. if ((rr->length == 0) || (s->rstate == SSL_ST_READ_BODY))
  890. {
  891. ret=ssl3_get_record(s);
  892. if (ret <= 0) return(ret);
  893. }
  894. /* we now have a packet which can be read and processed */
  895. if (s->s3->change_cipher_spec /* set when we receive ChangeCipherSpec,
  896. * reset by ssl3_get_finished */
  897. && (rr->type != SSL3_RT_HANDSHAKE))
  898. {
  899. al=SSL_AD_UNEXPECTED_MESSAGE;
  900. OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_DATA_BETWEEN_CCS_AND_FINISHED);
  901. goto f_err;
  902. }
  903. /* If the other end has shut down, throw anything we read away
  904. * (even in 'peek' mode) */
  905. if (s->shutdown & SSL_RECEIVED_SHUTDOWN)
  906. {
  907. rr->length=0;
  908. s->rwstate=SSL_NOTHING;
  909. return(0);
  910. }
  911. if (type == rr->type) /* SSL3_RT_APPLICATION_DATA or SSL3_RT_HANDSHAKE */
  912. {
  913. /* make sure that we are not getting application data when we
  914. * are doing a handshake for the first time */
  915. if (SSL_in_init(s) && (type == SSL3_RT_APPLICATION_DATA) &&
  916. (s->enc_read_ctx == NULL))
  917. {
  918. al=SSL_AD_UNEXPECTED_MESSAGE;
  919. OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_APP_DATA_IN_HANDSHAKE);
  920. goto f_err;
  921. }
  922. if (len <= 0) return(len);
  923. if ((unsigned int)len > rr->length)
  924. n = rr->length;
  925. else
  926. n = (unsigned int)len;
  927. memcpy(buf,&(rr->data[rr->off]),n);
  928. if (!peek)
  929. {
  930. rr->length-=n;
  931. rr->off+=n;
  932. if (rr->length == 0)
  933. {
  934. s->rstate=SSL_ST_READ_HEADER;
  935. rr->off=0;
  936. if (s->mode & SSL_MODE_RELEASE_BUFFERS && s->s3->rbuf.left == 0)
  937. ssl3_release_read_buffer(s);
  938. }
  939. }
  940. return(n);
  941. }
  942. /* If we get here, then type != rr->type; if we have a handshake
  943. * message, then it was unexpected (Hello Request or Client Hello). */
  944. /* In case of record types for which we have 'fragment' storage,
  945. * fill that so that we can process the data at a fixed place.
  946. */
  947. {
  948. unsigned int dest_maxlen = 0;
  949. unsigned char *dest = NULL;
  950. unsigned int *dest_len = NULL;
  951. if (rr->type == SSL3_RT_HANDSHAKE)
  952. {
  953. dest_maxlen = sizeof s->s3->handshake_fragment;
  954. dest = s->s3->handshake_fragment;
  955. dest_len = &s->s3->handshake_fragment_len;
  956. }
  957. else if (rr->type == SSL3_RT_ALERT)
  958. {
  959. dest_maxlen = sizeof s->s3->alert_fragment;
  960. dest = s->s3->alert_fragment;
  961. dest_len = &s->s3->alert_fragment_len;
  962. }
  963. if (dest_maxlen > 0)
  964. {
  965. n = dest_maxlen - *dest_len; /* available space in 'dest' */
  966. if (rr->length < n)
  967. n = rr->length; /* available bytes */
  968. /* now move 'n' bytes: */
  969. while (n-- > 0)
  970. {
  971. dest[(*dest_len)++] = rr->data[rr->off++];
  972. rr->length--;
  973. }
  974. if (*dest_len < dest_maxlen)
  975. goto start; /* fragment was too small */
  976. }
  977. }
  978. /* s->s3->handshake_fragment_len == 4 iff rr->type == SSL3_RT_HANDSHAKE;
  979. * s->s3->alert_fragment_len == 2 iff rr->type == SSL3_RT_ALERT.
  980. * (Possibly rr is 'empty' now, i.e. rr->length may be 0.) */
  981. /* If we are a client, check for an incoming 'Hello Request': */
  982. if ((!s->server) &&
  983. (s->s3->handshake_fragment_len >= 4) &&
  984. (s->s3->handshake_fragment[0] == SSL3_MT_HELLO_REQUEST) &&
  985. (s->session != NULL) && (s->session->cipher != NULL))
  986. {
  987. s->s3->handshake_fragment_len = 0;
  988. if ((s->s3->handshake_fragment[1] != 0) ||
  989. (s->s3->handshake_fragment[2] != 0) ||
  990. (s->s3->handshake_fragment[3] != 0))
  991. {
  992. al=SSL_AD_DECODE_ERROR;
  993. OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_BAD_HELLO_REQUEST);
  994. goto f_err;
  995. }
  996. if (s->msg_callback)
  997. s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE, s->s3->handshake_fragment, 4, s, s->msg_callback_arg);
  998. if (SSL_is_init_finished(s) &&
  999. !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS) &&
  1000. !s->s3->renegotiate)
  1001. {
  1002. ssl3_renegotiate(s);
  1003. if (ssl3_renegotiate_check(s))
  1004. {
  1005. i=s->handshake_func(s);
  1006. if (i < 0) return(i);
  1007. if (i == 0)
  1008. {
  1009. OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_SSL_HANDSHAKE_FAILURE);
  1010. return(-1);
  1011. }
  1012. if (!(s->mode & SSL_MODE_AUTO_RETRY))
  1013. {
  1014. if (s->s3->rbuf.left == 0) /* no read-ahead left? */
  1015. {
  1016. BIO *bio;
  1017. /* In the case where we try to read application data,
  1018. * but we trigger an SSL handshake, we return -1 with
  1019. * the retry option set. Otherwise renegotiation may
  1020. * cause nasty problems in the blocking world */
  1021. s->rwstate=SSL_READING;
  1022. bio=SSL_get_rbio(s);
  1023. BIO_clear_retry_flags(bio);
  1024. BIO_set_retry_read(bio);
  1025. return(-1);
  1026. }
  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 we are a server and get a client hello when renegotiation isn't
  1035. * allowed send back a no renegotiation alert and carry on.
  1036. * WARNING: experimental code, needs reviewing (steve)
  1037. */
  1038. if (s->server &&
  1039. SSL_is_init_finished(s) &&
  1040. !s->s3->send_connection_binding &&
  1041. (s->version > SSL3_VERSION) &&
  1042. (s->s3->handshake_fragment_len >= 4) &&
  1043. (s->s3->handshake_fragment[0] == SSL3_MT_CLIENT_HELLO) &&
  1044. (s->session != NULL) && (s->session->cipher != NULL) &&
  1045. !(s->ctx->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION))
  1046. {
  1047. /*s->s3->handshake_fragment_len = 0;*/
  1048. rr->length = 0;
  1049. ssl3_send_alert(s,SSL3_AL_WARNING, SSL_AD_NO_RENEGOTIATION);
  1050. goto start;
  1051. }
  1052. if (s->s3->alert_fragment_len >= 2)
  1053. {
  1054. int alert_level = s->s3->alert_fragment[0];
  1055. int alert_descr = s->s3->alert_fragment[1];
  1056. s->s3->alert_fragment_len = 0;
  1057. if (s->msg_callback)
  1058. s->msg_callback(0, s->version, SSL3_RT_ALERT, s->s3->alert_fragment, 2, s, s->msg_callback_arg);
  1059. if (s->info_callback != NULL)
  1060. cb=s->info_callback;
  1061. else if (s->ctx->info_callback != NULL)
  1062. cb=s->ctx->info_callback;
  1063. if (cb != NULL)
  1064. {
  1065. j = (alert_level << 8) | alert_descr;
  1066. cb(s, SSL_CB_READ_ALERT, j);
  1067. }
  1068. if (alert_level == 1) /* warning */
  1069. {
  1070. s->s3->warn_alert = alert_descr;
  1071. if (alert_descr == SSL_AD_CLOSE_NOTIFY)
  1072. {
  1073. s->shutdown |= SSL_RECEIVED_SHUTDOWN;
  1074. return(0);
  1075. }
  1076. /* This is a warning but we receive it if we requested
  1077. * renegotiation and the peer denied it. Terminate with
  1078. * a fatal alert because if application tried to
  1079. * renegotiatie it presumably had a good reason and
  1080. * expects it to succeed.
  1081. *
  1082. * In future we might have a renegotiation where we
  1083. * don't care if the peer refused it where we carry on.
  1084. */
  1085. else if (alert_descr == SSL_AD_NO_RENEGOTIATION)
  1086. {
  1087. al = SSL_AD_HANDSHAKE_FAILURE;
  1088. OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_NO_RENEGOTIATION);
  1089. goto f_err;
  1090. }
  1091. #ifdef SSL_AD_MISSING_SRP_USERNAME
  1092. else if (alert_descr == SSL_AD_MISSING_SRP_USERNAME)
  1093. return(0);
  1094. #endif
  1095. }
  1096. else if (alert_level == 2) /* fatal */
  1097. {
  1098. char tmp[16];
  1099. s->rwstate=SSL_NOTHING;
  1100. s->s3->fatal_alert = alert_descr;
  1101. OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_AD_REASON_OFFSET + alert_descr);
  1102. BIO_snprintf(tmp,sizeof tmp,"%d",alert_descr);
  1103. ERR_add_error_data(2,"SSL alert number ",tmp);
  1104. s->shutdown|=SSL_RECEIVED_SHUTDOWN;
  1105. SSL_CTX_remove_session(s->ctx,s->session);
  1106. return(0);
  1107. }
  1108. else
  1109. {
  1110. al=SSL_AD_ILLEGAL_PARAMETER;
  1111. OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_UNKNOWN_ALERT_TYPE);
  1112. goto f_err;
  1113. }
  1114. goto start;
  1115. }
  1116. if (s->shutdown & SSL_SENT_SHUTDOWN) /* but we have not received a shutdown */
  1117. {
  1118. s->rwstate=SSL_NOTHING;
  1119. rr->length=0;
  1120. return(0);
  1121. }
  1122. if (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC)
  1123. {
  1124. /* 'Change Cipher Spec' is just a single byte, so we know
  1125. * exactly what the record payload has to look like */
  1126. if ( (rr->length != 1) || (rr->off != 0) ||
  1127. (rr->data[0] != SSL3_MT_CCS))
  1128. {
  1129. al=SSL_AD_ILLEGAL_PARAMETER;
  1130. OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_BAD_CHANGE_CIPHER_SPEC);
  1131. goto f_err;
  1132. }
  1133. /* Check we have a cipher to change to */
  1134. if (s->s3->tmp.new_cipher == NULL)
  1135. {
  1136. al=SSL_AD_UNEXPECTED_MESSAGE;
  1137. OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_CCS_RECEIVED_EARLY);
  1138. goto f_err;
  1139. }
  1140. if (!(s->s3->flags & SSL3_FLAGS_CCS_OK))
  1141. {
  1142. al=SSL_AD_UNEXPECTED_MESSAGE;
  1143. OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_CCS_RECEIVED_EARLY);
  1144. goto f_err;
  1145. }
  1146. s->s3->flags &= ~SSL3_FLAGS_CCS_OK;
  1147. rr->length=0;
  1148. if (s->msg_callback)
  1149. s->msg_callback(0, s->version, SSL3_RT_CHANGE_CIPHER_SPEC, rr->data, 1, s, s->msg_callback_arg);
  1150. s->s3->change_cipher_spec=1;
  1151. if (!ssl3_do_change_cipher_spec(s))
  1152. goto err;
  1153. else
  1154. goto start;
  1155. }
  1156. /* Unexpected handshake message (Client Hello, or protocol violation) */
  1157. if ((s->s3->handshake_fragment_len >= 4) && !s->in_handshake)
  1158. {
  1159. if (((s->state&SSL_ST_MASK) == SSL_ST_OK) &&
  1160. !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS))
  1161. {
  1162. #if 0 /* worked only because C operator preferences are not as expected (and
  1163. * because this is not really needed for clients except for detecting
  1164. * protocol violations): */
  1165. s->state=SSL_ST_BEFORE|(s->server)
  1166. ?SSL_ST_ACCEPT
  1167. :SSL_ST_CONNECT;
  1168. #else
  1169. s->state = s->server ? SSL_ST_ACCEPT : SSL_ST_CONNECT;
  1170. #endif
  1171. s->renegotiate=1;
  1172. s->new_session=1;
  1173. }
  1174. i=s->handshake_func(s);
  1175. if (i < 0) return(i);
  1176. if (i == 0)
  1177. {
  1178. OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_SSL_HANDSHAKE_FAILURE);
  1179. return(-1);
  1180. }
  1181. if (!(s->mode & SSL_MODE_AUTO_RETRY))
  1182. {
  1183. if (s->s3->rbuf.left == 0) /* no read-ahead left? */
  1184. {
  1185. BIO *bio;
  1186. /* In the case where we try to read application data,
  1187. * but we trigger an SSL handshake, we return -1 with
  1188. * the retry option set. Otherwise renegotiation may
  1189. * cause nasty problems in the blocking world */
  1190. s->rwstate=SSL_READING;
  1191. bio=SSL_get_rbio(s);
  1192. BIO_clear_retry_flags(bio);
  1193. BIO_set_retry_read(bio);
  1194. return(-1);
  1195. }
  1196. }
  1197. goto start;
  1198. }
  1199. switch (rr->type)
  1200. {
  1201. default:
  1202. #ifndef OPENSSL_NO_TLS
  1203. /* TLS up to v1.1 just ignores unknown message types:
  1204. * TLS v1.2 give an unexpected message alert.
  1205. */
  1206. if (s->version >= TLS1_VERSION && s->version <= TLS1_1_VERSION)
  1207. {
  1208. rr->length = 0;
  1209. goto start;
  1210. }
  1211. #endif
  1212. al=SSL_AD_UNEXPECTED_MESSAGE;
  1213. OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_UNEXPECTED_RECORD);
  1214. goto f_err;
  1215. case SSL3_RT_CHANGE_CIPHER_SPEC:
  1216. case SSL3_RT_ALERT:
  1217. case SSL3_RT_HANDSHAKE:
  1218. /* we already handled all of these, with the possible exception
  1219. * of SSL3_RT_HANDSHAKE when s->in_handshake is set, but that
  1220. * should not happen when type != rr->type */
  1221. al=SSL_AD_UNEXPECTED_MESSAGE;
  1222. OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, ERR_R_INTERNAL_ERROR);
  1223. goto f_err;
  1224. case SSL3_RT_APPLICATION_DATA:
  1225. /* At this point, we were expecting handshake data,
  1226. * but have application data. If the library was
  1227. * running inside ssl3_read() (i.e. in_read_app_data
  1228. * is set) and it makes sense to read application data
  1229. * at this point (session renegotiation not yet started),
  1230. * we will indulge it.
  1231. */
  1232. if (s->s3->in_read_app_data &&
  1233. (s->s3->total_renegotiations != 0) &&
  1234. ((
  1235. (s->state & SSL_ST_CONNECT) &&
  1236. (s->state >= SSL3_ST_CW_CLNT_HELLO_A) &&
  1237. (s->state <= SSL3_ST_CR_SRVR_HELLO_A)
  1238. ) || (
  1239. (s->state & SSL_ST_ACCEPT) &&
  1240. (s->state <= SSL3_ST_SW_HELLO_REQ_A) &&
  1241. (s->state >= SSL3_ST_SR_CLNT_HELLO_A)
  1242. )
  1243. ))
  1244. {
  1245. s->s3->in_read_app_data=2;
  1246. return(-1);
  1247. }
  1248. else
  1249. {
  1250. al=SSL_AD_UNEXPECTED_MESSAGE;
  1251. OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_UNEXPECTED_RECORD);
  1252. goto f_err;
  1253. }
  1254. }
  1255. /* not reached */
  1256. f_err:
  1257. ssl3_send_alert(s,SSL3_AL_FATAL,al);
  1258. err:
  1259. return(-1);
  1260. }
  1261. int ssl3_do_change_cipher_spec(SSL *s)
  1262. {
  1263. int i;
  1264. const char *sender;
  1265. int slen;
  1266. if (s->state & SSL_ST_ACCEPT)
  1267. i=SSL3_CHANGE_CIPHER_SERVER_READ;
  1268. else
  1269. i=SSL3_CHANGE_CIPHER_CLIENT_READ;
  1270. if (s->s3->tmp.key_block == NULL)
  1271. {
  1272. if (s->session == NULL || s->session->master_key_length == 0)
  1273. {
  1274. /* might happen if dtls1_read_bytes() calls this */
  1275. OPENSSL_PUT_ERROR(SSL, ssl3_do_change_cipher_spec, SSL_R_CCS_RECEIVED_EARLY);
  1276. return (0);
  1277. }
  1278. s->session->cipher=s->s3->tmp.new_cipher;
  1279. if (!s->method->ssl3_enc->setup_key_block(s)) return(0);
  1280. }
  1281. if (!s->method->ssl3_enc->change_cipher_state(s,i))
  1282. return(0);
  1283. /* we have to record the message digest at
  1284. * this point so we can get it before we read
  1285. * the finished message */
  1286. if (s->state & SSL_ST_CONNECT)
  1287. {
  1288. sender=s->method->ssl3_enc->server_finished_label;
  1289. slen=s->method->ssl3_enc->server_finished_label_len;
  1290. }
  1291. else
  1292. {
  1293. sender=s->method->ssl3_enc->client_finished_label;
  1294. slen=s->method->ssl3_enc->client_finished_label_len;
  1295. }
  1296. i = s->method->ssl3_enc->final_finish_mac(s,
  1297. sender,slen,s->s3->tmp.peer_finish_md);
  1298. if (i == 0)
  1299. {
  1300. OPENSSL_PUT_ERROR(SSL, ssl3_do_change_cipher_spec, ERR_R_INTERNAL_ERROR);
  1301. return 0;
  1302. }
  1303. s->s3->tmp.peer_finish_md_len = i;
  1304. return(1);
  1305. }
  1306. int ssl3_send_alert(SSL *s, int level, int desc)
  1307. {
  1308. /* Map tls/ssl alert value to correct one */
  1309. desc=s->method->ssl3_enc->alert_value(desc);
  1310. if (s->version == SSL3_VERSION && desc == SSL_AD_PROTOCOL_VERSION)
  1311. desc = SSL_AD_HANDSHAKE_FAILURE; /* SSL 3.0 does not have protocol_version alerts */
  1312. if (desc < 0) return -1;
  1313. /* If a fatal one, remove from cache */
  1314. if ((level == 2) && (s->session != NULL))
  1315. SSL_CTX_remove_session(s->ctx,s->session);
  1316. s->s3->alert_dispatch=1;
  1317. s->s3->send_alert[0]=level;
  1318. s->s3->send_alert[1]=desc;
  1319. if (s->s3->wbuf.left == 0) /* data still being written out? */
  1320. return s->method->ssl_dispatch_alert(s);
  1321. /* else data is still being written out, we will get written
  1322. * some time in the future */
  1323. return -1;
  1324. }
  1325. int ssl3_dispatch_alert(SSL *s)
  1326. {
  1327. int i,j;
  1328. void (*cb)(const SSL *ssl,int type,int val)=NULL;
  1329. s->s3->alert_dispatch=0;
  1330. i = do_ssl3_write(s, SSL3_RT_ALERT, &s->s3->send_alert[0], 2, 0, 0);
  1331. if (i <= 0)
  1332. {
  1333. s->s3->alert_dispatch=1;
  1334. }
  1335. else
  1336. {
  1337. /* Alert sent to BIO. If it is important, flush it now.
  1338. * If the message does not get sent due to non-blocking IO,
  1339. * we will not worry too much. */
  1340. if (s->s3->send_alert[0] == SSL3_AL_FATAL)
  1341. (void)BIO_flush(s->wbio);
  1342. if (s->msg_callback)
  1343. s->msg_callback(1, s->version, SSL3_RT_ALERT, s->s3->send_alert, 2, s, s->msg_callback_arg);
  1344. if (s->info_callback != NULL)
  1345. cb=s->info_callback;
  1346. else if (s->ctx->info_callback != NULL)
  1347. cb=s->ctx->info_callback;
  1348. if (cb != NULL)
  1349. {
  1350. j=(s->s3->send_alert[0]<<8)|s->s3->send_alert[1];
  1351. cb(s,SSL_CB_WRITE_ALERT,j);
  1352. }
  1353. }
  1354. return(i);
  1355. }