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

s3_pkt.c 38 KiB

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