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.

s3_pkt.c 37 KiB

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