s3_pkt.c 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418
  1. /* ssl/s3_pkt.c */
  2. /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
  3. * All rights reserved.
  4. *
  5. * This package is an SSL implementation written
  6. * by Eric Young (eay@cryptsoft.com).
  7. * The implementation was written so as to conform with Netscapes SSL.
  8. *
  9. * This library is free for commercial and non-commercial use as long as
  10. * the following conditions are aheared to. The following conditions
  11. * apply to all code found in this distribution, be it the RC4, RSA,
  12. * lhash, DES, etc., code; not just the SSL code. The SSL documentation
  13. * included with this distribution is covered by the same copyright terms
  14. * except that the holder is Tim Hudson (tjh@cryptsoft.com).
  15. *
  16. * Copyright remains Eric Young's, and as such any Copyright notices in
  17. * the code are not to be removed.
  18. * If this package is used in a product, Eric Young should be given attribution
  19. * as the author of the parts of the library used.
  20. * This can be in the form of a textual message at program startup or
  21. * in documentation (online or textual) provided with the package.
  22. *
  23. * Redistribution and use in source and binary forms, with or without
  24. * modification, are permitted provided that the following conditions
  25. * are met:
  26. * 1. Redistributions of source code must retain the copyright
  27. * notice, this list of conditions and the following disclaimer.
  28. * 2. Redistributions in binary form must reproduce the above copyright
  29. * notice, this list of conditions and the following disclaimer in the
  30. * documentation and/or other materials provided with the distribution.
  31. * 3. All advertising materials mentioning features or use of this software
  32. * must display the following acknowledgement:
  33. * "This product includes cryptographic software written by
  34. * Eric Young (eay@cryptsoft.com)"
  35. * The word 'cryptographic' can be left out if the rouines from the library
  36. * being used are not cryptographic related :-).
  37. * 4. If you include any Windows specific code (or a derivative thereof) from
  38. * the apps directory (application code) you must include an acknowledgement:
  39. * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
  40. *
  41. * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
  42. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  43. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  44. * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
  45. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  46. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  47. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  48. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  49. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  50. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  51. * SUCH DAMAGE.
  52. *
  53. * The licence and distribution terms for any publically available version or
  54. * derivative of this code cannot be changed. i.e. this code cannot simply be
  55. * copied and put under another distribution licence
  56. * [including the GNU Public Licence.]
  57. */
  58. /* ====================================================================
  59. * Copyright (c) 1998-2002 The OpenSSL Project. All rights reserved.
  60. *
  61. * Redistribution and use in source and binary forms, with or without
  62. * modification, are permitted provided that the following conditions
  63. * are met:
  64. *
  65. * 1. Redistributions of source code must retain the above copyright
  66. * notice, this list of conditions and the following disclaimer.
  67. *
  68. * 2. Redistributions in binary form must reproduce the above copyright
  69. * notice, this list of conditions and the following disclaimer in
  70. * the documentation and/or other materials provided with the
  71. * distribution.
  72. *
  73. * 3. All advertising materials mentioning features or use of this
  74. * software must display the following acknowledgment:
  75. * "This product includes software developed by the OpenSSL Project
  76. * for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
  77. *
  78. * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
  79. * endorse or promote products derived from this software without
  80. * prior written permission. For written permission, please contact
  81. * openssl-core@openssl.org.
  82. *
  83. * 5. Products derived from this software may not be called "OpenSSL"
  84. * nor may "OpenSSL" appear in their names without prior written
  85. * permission of the OpenSSL Project.
  86. *
  87. * 6. Redistributions of any form whatsoever must retain the following
  88. * acknowledgment:
  89. * "This product includes software developed by the OpenSSL Project
  90. * for use in the OpenSSL Toolkit (http://www.openssl.org/)"
  91. *
  92. * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
  93. * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  94. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  95. * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
  96. * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  97. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  98. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  99. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  100. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  101. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  102. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
  103. * OF THE POSSIBILITY OF SUCH DAMAGE.
  104. * ====================================================================
  105. *
  106. * This product includes cryptographic software written by Eric Young
  107. * (eay@cryptsoft.com). This product includes software written by Tim
  108. * Hudson (tjh@cryptsoft.com).
  109. *
  110. */
  111. #include <stdio.h>
  112. #include <limits.h>
  113. #include <errno.h>
  114. #define USE_SOCKETS
  115. #include "ssl_locl.h"
  116. #include <openssl/evp.h>
  117. #include <openssl/buffer.h>
  118. static int do_ssl3_write(SSL *s, int type, const unsigned char *buf,
  119. unsigned int len, int create_empty_fragment);
  120. static int ssl3_get_record(SSL *s);
  121. int ssl3_read_n(SSL *s, int n, int max, int extend)
  122. {
  123. /*
  124. * If extend == 0, obtain new n-byte packet; if extend == 1, increase
  125. * packet by another n bytes. The packet will be in the sub-array of
  126. * s->s3->rbuf.buf specified by s->packet and s->packet_length. (If
  127. * s->read_ahead is set, 'max' bytes may be stored in rbuf [plus
  128. * s->packet_length bytes if extend == 1].)
  129. */
  130. int i, off, newb;
  131. if (!extend) {
  132. /* start with empty packet ... */
  133. if (s->s3->rbuf.left == 0)
  134. s->s3->rbuf.offset = 0;
  135. s->packet = s->s3->rbuf.buf + s->s3->rbuf.offset;
  136. s->packet_length = 0;
  137. /* ... now we can act as if 'extend' was set */
  138. }
  139. /*
  140. * For DTLS/UDP reads should not span multiple packets because the read
  141. * operation returns the whole packet at once (as long as it fits into
  142. * the buffer).
  143. */
  144. if (SSL_version(s) == DTLS1_VERSION) {
  145. if (s->s3->rbuf.left == 0 && extend)
  146. return 0;
  147. if (s->s3->rbuf.left > 0 && n > s->s3->rbuf.left)
  148. n = s->s3->rbuf.left;
  149. }
  150. /* if there is enough in the buffer from a previous read, take some */
  151. if (s->s3->rbuf.left >= (int)n) {
  152. s->packet_length += n;
  153. s->s3->rbuf.left -= n;
  154. s->s3->rbuf.offset += n;
  155. return (n);
  156. }
  157. /* else we need to read more data */
  158. if (!s->read_ahead)
  159. max = n;
  160. {
  161. /* avoid buffer overflow */
  162. int max_max = s->s3->rbuf.len - s->packet_length;
  163. if (max > max_max)
  164. max = max_max;
  165. }
  166. if (n > max) { /* does not happen */
  167. SSLerr(SSL_F_SSL3_READ_N, ERR_R_INTERNAL_ERROR);
  168. return -1;
  169. }
  170. off = s->packet_length;
  171. newb = s->s3->rbuf.left;
  172. /*
  173. * Move any available bytes to front of buffer: 'off' bytes already
  174. * pointed to by 'packet', 'newb' extra ones at the end
  175. */
  176. if (s->packet != s->s3->rbuf.buf) {
  177. /* off > 0 */
  178. memmove(s->s3->rbuf.buf, s->packet, off + newb);
  179. s->packet = s->s3->rbuf.buf;
  180. }
  181. while (newb < n) {
  182. /*
  183. * Now we have off+newb bytes at the front of s->s3->rbuf.buf and
  184. * need to read in more until we have off+n (up to off+max if
  185. * possible)
  186. */
  187. clear_sys_error();
  188. if (s->rbio != NULL) {
  189. s->rwstate = SSL_READING;
  190. i = BIO_read(s->rbio, &(s->s3->rbuf.buf[off + newb]), max - newb);
  191. } else {
  192. SSLerr(SSL_F_SSL3_READ_N, SSL_R_READ_BIO_NOT_SET);
  193. i = -1;
  194. }
  195. if (i <= 0) {
  196. s->s3->rbuf.left = newb;
  197. return (i);
  198. }
  199. newb += i;
  200. /*
  201. * reads should *never* span multiple packets for DTLS because the
  202. * underlying transport protocol is message oriented as opposed to
  203. * byte oriented as in the TLS case.
  204. */
  205. if (SSL_version(s) == DTLS1_VERSION) {
  206. if (n > newb)
  207. n = newb; /* makes the while condition false */
  208. }
  209. }
  210. /* done reading, now the book-keeping */
  211. s->s3->rbuf.offset = off + n;
  212. s->s3->rbuf.left = newb - n;
  213. s->packet_length += n;
  214. s->rwstate = SSL_NOTHING;
  215. return (n);
  216. }
  217. /*
  218. * MAX_EMPTY_RECORDS defines the number of consecutive, empty records that
  219. * will be processed per call to ssl3_get_record. Without this limit an
  220. * attacker could send empty records at a faster rate than we can process and
  221. * cause ssl3_get_record to loop forever.
  222. */
  223. #define MAX_EMPTY_RECORDS 32
  224. /*-
  225. * Call this to get a new input record.
  226. * It will return <= 0 if more data is needed, normally due to an error
  227. * or non-blocking IO.
  228. * When it finishes, one packet has been decoded and can be found in
  229. * ssl->s3->rrec.type - is the type of record
  230. * ssl->s3->rrec.data, - data
  231. * ssl->s3->rrec.length, - number of bytes
  232. */
  233. /* used only by ssl3_read_bytes */
  234. static int ssl3_get_record(SSL *s)
  235. {
  236. int ssl_major, ssl_minor, al;
  237. int enc_err, n, i, ret = -1;
  238. SSL3_RECORD *rr;
  239. SSL_SESSION *sess;
  240. unsigned char *p;
  241. unsigned char md[EVP_MAX_MD_SIZE];
  242. short version;
  243. unsigned mac_size, orig_len;
  244. size_t extra;
  245. unsigned empty_record_count = 0;
  246. rr = &(s->s3->rrec);
  247. sess = s->session;
  248. if (s->options & SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER)
  249. extra = SSL3_RT_MAX_EXTRA;
  250. else
  251. extra = 0;
  252. if (extra != s->s3->rbuf.len - SSL3_RT_MAX_PACKET_SIZE) {
  253. /*
  254. * actually likely an application error:
  255. * SLS_OP_MICROSOFT_BIG_SSLV3_BUFFER set after ssl3_setup_buffers()
  256. * was done
  257. */
  258. SSLerr(SSL_F_SSL3_GET_RECORD, ERR_R_INTERNAL_ERROR);
  259. return -1;
  260. }
  261. again:
  262. /* check if we have the header */
  263. if ((s->rstate != SSL_ST_READ_BODY) ||
  264. (s->packet_length < SSL3_RT_HEADER_LENGTH)) {
  265. n = ssl3_read_n(s, SSL3_RT_HEADER_LENGTH, s->s3->rbuf.len, 0);
  266. if (n <= 0)
  267. return (n); /* error or non-blocking */
  268. s->rstate = SSL_ST_READ_BODY;
  269. p = s->packet;
  270. /* Pull apart the header into the SSL3_RECORD */
  271. rr->type = *(p++);
  272. ssl_major = *(p++);
  273. ssl_minor = *(p++);
  274. version = (ssl_major << 8) | ssl_minor;
  275. n2s(p, rr->length);
  276. /* Lets check version */
  277. if (!s->first_packet) {
  278. if (version != s->version) {
  279. SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_WRONG_VERSION_NUMBER);
  280. if ((s->version & 0xFF00) == (version & 0xFF00))
  281. /*
  282. * Send back error using their minor version number :-)
  283. */
  284. s->version = (unsigned short)version;
  285. al = SSL_AD_PROTOCOL_VERSION;
  286. goto f_err;
  287. }
  288. }
  289. if ((version >> 8) != SSL3_VERSION_MAJOR) {
  290. SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_WRONG_VERSION_NUMBER);
  291. goto err;
  292. }
  293. if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH + extra) {
  294. al = SSL_AD_RECORD_OVERFLOW;
  295. SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_PACKET_LENGTH_TOO_LONG);
  296. goto f_err;
  297. }
  298. /* now s->rstate == SSL_ST_READ_BODY */
  299. }
  300. /* s->rstate == SSL_ST_READ_BODY, get and decode the data */
  301. if (rr->length > s->packet_length - SSL3_RT_HEADER_LENGTH) {
  302. /* now s->packet_length == SSL3_RT_HEADER_LENGTH */
  303. i = rr->length;
  304. n = ssl3_read_n(s, i, i, 1);
  305. if (n <= 0)
  306. return (n); /* error or non-blocking io */
  307. /*
  308. * now n == rr->length, and s->packet_length == SSL3_RT_HEADER_LENGTH
  309. * + rr->length
  310. */
  311. }
  312. s->rstate = SSL_ST_READ_HEADER; /* set state for later operations */
  313. /*
  314. * At this point, s->packet_length == SSL3_RT_HEADER_LNGTH + rr->length,
  315. * and we have that many bytes in s->packet
  316. */
  317. rr->input = &(s->packet[SSL3_RT_HEADER_LENGTH]);
  318. /*
  319. * ok, we can now read from 's->packet' data into 'rr' rr->input points
  320. * at rr->length bytes, which need to be copied into rr->data by either
  321. * the decryption or by the decompression When the data is 'copied' into
  322. * the rr->data buffer, rr->input will be pointed at the new buffer
  323. */
  324. /*
  325. * We now have - encrypted [ MAC [ compressed [ plain ] ] ] rr->length
  326. * bytes of encrypted compressed stuff.
  327. */
  328. /* check is not needed I believe */
  329. if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH + extra) {
  330. al = SSL_AD_RECORD_OVERFLOW;
  331. SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
  332. goto f_err;
  333. }
  334. /* decrypt in place in 'rr->input' */
  335. rr->data = rr->input;
  336. enc_err = s->method->ssl3_enc->enc(s, 0);
  337. /*-
  338. * enc_err is:
  339. * 0: (in non-constant time) if the record is publically invalid.
  340. * 1: if the padding is valid
  341. * -1: if the padding is invalid
  342. */
  343. if (enc_err == 0) {
  344. al = SSL_AD_DECRYPTION_FAILED;
  345. SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_BLOCK_CIPHER_PAD_IS_WRONG);
  346. goto f_err;
  347. }
  348. #ifdef TLS_DEBUG
  349. printf("dec %d\n", rr->length);
  350. {
  351. unsigned int z;
  352. for (z = 0; z < rr->length; z++)
  353. printf("%02X%c", rr->data[z], ((z + 1) % 16) ? ' ' : '\n');
  354. }
  355. printf("\n");
  356. #endif
  357. /* r->length is now the compressed data plus mac */
  358. if ((sess != NULL) && (s->enc_read_ctx != NULL) && (s->read_hash != NULL)) {
  359. /* s->read_hash != NULL => mac_size != -1 */
  360. unsigned char *mac = NULL;
  361. unsigned char mac_tmp[EVP_MAX_MD_SIZE];
  362. mac_size = EVP_MD_size(s->read_hash);
  363. OPENSSL_assert(mac_size <= EVP_MAX_MD_SIZE);
  364. /*
  365. * kludge: *_cbc_remove_padding passes padding length in rr->type
  366. */
  367. orig_len = rr->length + ((unsigned int)rr->type >> 8);
  368. /*
  369. * orig_len is the length of the record before any padding was
  370. * removed. This is public information, as is the MAC in use,
  371. * therefore we can safely process the record in a different amount
  372. * of time if it's too short to possibly contain a MAC.
  373. */
  374. if (orig_len < mac_size ||
  375. /* CBC records must have a padding length byte too. */
  376. (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
  377. orig_len < mac_size + 1)) {
  378. al = SSL_AD_DECODE_ERROR;
  379. SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_LENGTH_TOO_SHORT);
  380. goto f_err;
  381. }
  382. if (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE) {
  383. /*
  384. * We update the length so that the TLS header bytes can be
  385. * constructed correctly but we need to extract the MAC in
  386. * constant time from within the record, without leaking the
  387. * contents of the padding bytes.
  388. */
  389. mac = mac_tmp;
  390. ssl3_cbc_copy_mac(mac_tmp, rr, mac_size, orig_len);
  391. rr->length -= mac_size;
  392. } else {
  393. /*
  394. * In this case there's no padding, so |orig_len| equals
  395. * |rec->length| and we checked that there's enough bytes for
  396. * |mac_size| above.
  397. */
  398. rr->length -= mac_size;
  399. mac = &rr->data[rr->length];
  400. }
  401. i = s->method->ssl3_enc->mac(s, md, 0 /* not send */ );
  402. if (i < 0 || mac == NULL
  403. || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0)
  404. enc_err = -1;
  405. if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH + extra + mac_size)
  406. enc_err = -1;
  407. }
  408. if (enc_err < 0) {
  409. /*
  410. * A separate 'decryption_failed' alert was introduced with TLS 1.0,
  411. * SSL 3.0 only has 'bad_record_mac'. But unless a decryption
  412. * failure is directly visible from the ciphertext anyway, we should
  413. * not reveal which kind of error occured -- this might become
  414. * visible to an attacker (e.g. via a logfile)
  415. */
  416. al = SSL_AD_BAD_RECORD_MAC;
  417. SSLerr(SSL_F_SSL3_GET_RECORD,
  418. SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
  419. goto f_err;
  420. }
  421. /* r->length is now just compressed */
  422. if (s->expand != NULL) {
  423. if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH + extra) {
  424. al = SSL_AD_RECORD_OVERFLOW;
  425. SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_COMPRESSED_LENGTH_TOO_LONG);
  426. goto f_err;
  427. }
  428. if (!ssl3_do_uncompress(s)) {
  429. al = SSL_AD_DECOMPRESSION_FAILURE;
  430. SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_BAD_DECOMPRESSION);
  431. goto f_err;
  432. }
  433. }
  434. if (rr->length > SSL3_RT_MAX_PLAIN_LENGTH + extra) {
  435. al = SSL_AD_RECORD_OVERFLOW;
  436. SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_DATA_LENGTH_TOO_LONG);
  437. goto f_err;
  438. }
  439. rr->off = 0;
  440. /*-
  441. * So at this point the following is true
  442. * ssl->s3->rrec.type is the type of record
  443. * ssl->s3->rrec.length == number of bytes in record
  444. * ssl->s3->rrec.off == offset to first valid byte
  445. * ssl->s3->rrec.data == where to take bytes from, increment
  446. * after use :-).
  447. */
  448. /* we have pulled in a full packet so zero things */
  449. s->packet_length = 0;
  450. /* just read a 0 length packet */
  451. if (rr->length == 0) {
  452. empty_record_count++;
  453. if (empty_record_count > MAX_EMPTY_RECORDS) {
  454. al = SSL_AD_UNEXPECTED_MESSAGE;
  455. SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_RECORD_TOO_SMALL);
  456. goto f_err;
  457. }
  458. goto again;
  459. }
  460. return (1);
  461. f_err:
  462. ssl3_send_alert(s, SSL3_AL_FATAL, al);
  463. err:
  464. return (ret);
  465. }
  466. int ssl3_do_uncompress(SSL *ssl)
  467. {
  468. #ifndef OPENSSL_NO_COMP
  469. int i;
  470. SSL3_RECORD *rr;
  471. rr = &(ssl->s3->rrec);
  472. i = COMP_expand_block(ssl->expand, rr->comp,
  473. SSL3_RT_MAX_PLAIN_LENGTH, rr->data,
  474. (int)rr->length);
  475. if (i < 0)
  476. return (0);
  477. else
  478. rr->length = i;
  479. rr->data = rr->comp;
  480. #endif
  481. return (1);
  482. }
  483. int ssl3_do_compress(SSL *ssl)
  484. {
  485. #ifndef OPENSSL_NO_COMP
  486. int i;
  487. SSL3_RECORD *wr;
  488. wr = &(ssl->s3->wrec);
  489. i = COMP_compress_block(ssl->compress, wr->data,
  490. SSL3_RT_MAX_COMPRESSED_LENGTH,
  491. wr->input, (int)wr->length);
  492. if (i < 0)
  493. return (0);
  494. else
  495. wr->length = i;
  496. wr->input = wr->data;
  497. #endif
  498. return (1);
  499. }
  500. /*
  501. * Call this to write data in records of type 'type' It will return <= 0 if
  502. * not all data has been sent or non-blocking IO.
  503. */
  504. int ssl3_write_bytes(SSL *s, int type, const void *buf_, int len)
  505. {
  506. const unsigned char *buf = buf_;
  507. unsigned int n, nw;
  508. int i, tot;
  509. s->rwstate = SSL_NOTHING;
  510. OPENSSL_assert(s->s3->wnum <= INT_MAX);
  511. tot = s->s3->wnum;
  512. s->s3->wnum = 0;
  513. if (SSL_in_init(s) && !s->in_handshake) {
  514. i = s->handshake_func(s);
  515. if (i < 0)
  516. return (i);
  517. if (i == 0) {
  518. SSLerr(SSL_F_SSL3_WRITE_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE);
  519. return -1;
  520. }
  521. }
  522. /*
  523. * ensure that if we end up with a smaller value of data to write out
  524. * than the the original len from a write which didn't complete for
  525. * non-blocking I/O and also somehow ended up avoiding the check for
  526. * this in ssl3_write_pending/SSL_R_BAD_WRITE_RETRY as it must never be
  527. * possible to end up with (len-tot) as a large number that will then
  528. * promptly send beyond the end of the users buffer ... so we trap and
  529. * report the error in a way the user will notice
  530. */
  531. if (len < tot) {
  532. SSLerr(SSL_F_SSL3_WRITE_BYTES, SSL_R_BAD_LENGTH);
  533. return (-1);
  534. }
  535. n = (len - tot);
  536. for (;;) {
  537. if (n > SSL3_RT_MAX_PLAIN_LENGTH)
  538. nw = SSL3_RT_MAX_PLAIN_LENGTH;
  539. else
  540. nw = n;
  541. i = do_ssl3_write(s, type, &(buf[tot]), nw, 0);
  542. if (i <= 0) {
  543. s->s3->wnum = tot;
  544. return i;
  545. }
  546. if ((i == (int)n) ||
  547. (type == SSL3_RT_APPLICATION_DATA &&
  548. (s->mode & SSL_MODE_ENABLE_PARTIAL_WRITE))) {
  549. /*
  550. * next chunk of data should get another prepended empty fragment
  551. * in ciphersuites with known-IV weakness:
  552. */
  553. s->s3->empty_fragment_done = 0;
  554. return tot + i;
  555. }
  556. n -= i;
  557. tot += i;
  558. }
  559. }
  560. static int do_ssl3_write(SSL *s, int type, const unsigned char *buf,
  561. unsigned int len, int create_empty_fragment)
  562. {
  563. unsigned char *p, *plen;
  564. int i, mac_size, clear = 0;
  565. int prefix_len = 0;
  566. SSL3_RECORD *wr;
  567. SSL3_BUFFER *wb;
  568. SSL_SESSION *sess;
  569. /*
  570. * first check if there is a SSL3_BUFFER still being written out. This
  571. * will happen with non blocking IO
  572. */
  573. if (s->s3->wbuf.left != 0)
  574. return (ssl3_write_pending(s, type, buf, len));
  575. /* If we have an alert to send, lets send it */
  576. if (s->s3->alert_dispatch) {
  577. i = s->method->ssl_dispatch_alert(s);
  578. if (i <= 0)
  579. return (i);
  580. /* if it went, fall through and send more stuff */
  581. }
  582. if (len == 0 && !create_empty_fragment)
  583. return 0;
  584. wr = &(s->s3->wrec);
  585. wb = &(s->s3->wbuf);
  586. sess = s->session;
  587. if ((sess == NULL) ||
  588. (s->enc_write_ctx == NULL) || (s->write_hash == NULL))
  589. clear = 1;
  590. if (clear)
  591. mac_size = 0;
  592. else
  593. mac_size = EVP_MD_size(s->write_hash);
  594. /*
  595. * 'create_empty_fragment' is true only when this function calls itself
  596. */
  597. if (!clear && !create_empty_fragment && !s->s3->empty_fragment_done) {
  598. /*
  599. * countermeasure against known-IV weakness in CBC ciphersuites (see
  600. * http://www.openssl.org/~bodo/tls-cbc.txt)
  601. */
  602. if (s->s3->need_empty_fragments && type == SSL3_RT_APPLICATION_DATA) {
  603. /*
  604. * recursive function call with 'create_empty_fragment' set; this
  605. * prepares and buffers the data for an empty fragment (these
  606. * 'prefix_len' bytes are sent out later together with the actual
  607. * payload)
  608. */
  609. prefix_len = do_ssl3_write(s, type, buf, 0, 1);
  610. if (prefix_len <= 0)
  611. goto err;
  612. if (s->s3->wbuf.len <
  613. (size_t)prefix_len + SSL3_RT_MAX_PACKET_SIZE) {
  614. /* insufficient space */
  615. SSLerr(SSL_F_DO_SSL3_WRITE, ERR_R_INTERNAL_ERROR);
  616. goto err;
  617. }
  618. }
  619. s->s3->empty_fragment_done = 1;
  620. }
  621. p = wb->buf + prefix_len;
  622. /* write the header */
  623. *(p++) = type & 0xff;
  624. wr->type = type;
  625. *(p++) = (s->version >> 8);
  626. *(p++) = s->version & 0xff;
  627. /* field where we are to write out packet length */
  628. plen = p;
  629. p += 2;
  630. /* lets setup the record stuff. */
  631. wr->data = p;
  632. wr->length = (int)len;
  633. wr->input = (unsigned char *)buf;
  634. /*
  635. * we now 'read' from wr->input, wr->length bytes into wr->data
  636. */
  637. /* first we compress */
  638. if (s->compress != NULL) {
  639. if (!ssl3_do_compress(s)) {
  640. SSLerr(SSL_F_DO_SSL3_WRITE, SSL_R_COMPRESSION_FAILURE);
  641. goto err;
  642. }
  643. } else {
  644. memcpy(wr->data, wr->input, wr->length);
  645. wr->input = wr->data;
  646. }
  647. /*
  648. * we should still have the output to wr->data and the input from
  649. * wr->input. Length should be wr->length. wr->data still points in the
  650. * wb->buf
  651. */
  652. if (mac_size != 0) {
  653. s->method->ssl3_enc->mac(s, &(p[wr->length]), 1);
  654. wr->length += mac_size;
  655. wr->input = p;
  656. wr->data = p;
  657. }
  658. /* ssl3_enc can only have an error on read */
  659. s->method->ssl3_enc->enc(s, 1);
  660. /* record length after mac and block padding */
  661. s2n(wr->length, plen);
  662. /*
  663. * we should now have wr->data pointing to the encrypted data, which is
  664. * wr->length long
  665. */
  666. wr->type = type; /* not needed but helps for debugging */
  667. wr->length += SSL3_RT_HEADER_LENGTH;
  668. if (create_empty_fragment) {
  669. /*
  670. * we are in a recursive call; just return the length, don't write
  671. * out anything here
  672. */
  673. return wr->length;
  674. }
  675. /* now let's set up wb */
  676. wb->left = prefix_len + wr->length;
  677. wb->offset = 0;
  678. /*
  679. * memorize arguments so that ssl3_write_pending can detect bad write
  680. * retries later
  681. */
  682. s->s3->wpend_tot = len;
  683. s->s3->wpend_buf = buf;
  684. s->s3->wpend_type = type;
  685. s->s3->wpend_ret = len;
  686. /* we now just need to write the buffer */
  687. return ssl3_write_pending(s, type, buf, len);
  688. err:
  689. return -1;
  690. }
  691. /* if s->s3->wbuf.left != 0, we need to call this */
  692. int ssl3_write_pending(SSL *s, int type, const unsigned char *buf,
  693. unsigned int len)
  694. {
  695. int i;
  696. /* XXXX */
  697. if ((s->s3->wpend_tot > (int)len)
  698. || ((s->s3->wpend_buf != buf) &&
  699. !(s->mode & SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER))
  700. || (s->s3->wpend_type != type)) {
  701. SSLerr(SSL_F_SSL3_WRITE_PENDING, SSL_R_BAD_WRITE_RETRY);
  702. return (-1);
  703. }
  704. for (;;) {
  705. clear_sys_error();
  706. if (s->wbio != NULL) {
  707. s->rwstate = SSL_WRITING;
  708. i = BIO_write(s->wbio,
  709. (char *)&(s->s3->wbuf.buf[s->s3->wbuf.offset]),
  710. (unsigned int)s->s3->wbuf.left);
  711. } else {
  712. SSLerr(SSL_F_SSL3_WRITE_PENDING, SSL_R_BIO_NOT_SET);
  713. i = -1;
  714. }
  715. if (i == s->s3->wbuf.left) {
  716. s->s3->wbuf.left = 0;
  717. s->rwstate = SSL_NOTHING;
  718. return (s->s3->wpend_ret);
  719. } else if (i <= 0) {
  720. if (s->version == DTLS1_VERSION || s->version == DTLS1_BAD_VER) {
  721. /*
  722. * For DTLS, just drop it. That's kind of the whole point in
  723. * using a datagram service
  724. */
  725. s->s3->wbuf.left = 0;
  726. }
  727. return (i);
  728. }
  729. s->s3->wbuf.offset += i;
  730. s->s3->wbuf.left -= i;
  731. }
  732. }
  733. /*-
  734. * Return up to 'len' payload bytes received in 'type' records.
  735. * 'type' is one of the following:
  736. *
  737. * - SSL3_RT_HANDSHAKE (when ssl3_get_message calls us)
  738. * - SSL3_RT_APPLICATION_DATA (when ssl3_read calls us)
  739. * - 0 (during a shutdown, no data has to be returned)
  740. *
  741. * If we don't have stored data to work from, read a SSL/TLS record first
  742. * (possibly multiple records if we still don't have anything to return).
  743. *
  744. * This function must handle any surprises the peer may have for us, such as
  745. * Alert records (e.g. close_notify), ChangeCipherSpec records (not really
  746. * a surprise, but handled as if it were), or renegotiation requests.
  747. * Also if record payloads contain fragments too small to process, we store
  748. * them until there is enough for the respective protocol (the record protocol
  749. * may use arbitrary fragmentation and even interleaving):
  750. * Change cipher spec protocol
  751. * just 1 byte needed, no need for keeping anything stored
  752. * Alert protocol
  753. * 2 bytes needed (AlertLevel, AlertDescription)
  754. * Handshake protocol
  755. * 4 bytes needed (HandshakeType, uint24 length) -- we just have
  756. * to detect unexpected Client Hello and Hello Request messages
  757. * here, anything else is handled by higher layers
  758. * Application data protocol
  759. * none of our business
  760. */
  761. int ssl3_read_bytes(SSL *s, int type, unsigned char *buf, int len, int peek)
  762. {
  763. int al, i, j, ret;
  764. unsigned int n;
  765. SSL3_RECORD *rr;
  766. void (*cb) (const SSL *ssl, int type2, int val) = NULL;
  767. if (s->s3->rbuf.buf == NULL) /* Not initialized yet */
  768. if (!ssl3_setup_buffers(s))
  769. return (-1);
  770. if ((type && (type != SSL3_RT_APPLICATION_DATA)
  771. && (type != SSL3_RT_HANDSHAKE)) || (peek
  772. && (type !=
  773. SSL3_RT_APPLICATION_DATA))) {
  774. SSLerr(SSL_F_SSL3_READ_BYTES, ERR_R_INTERNAL_ERROR);
  775. return -1;
  776. }
  777. if ((type == SSL3_RT_HANDSHAKE) && (s->s3->handshake_fragment_len > 0))
  778. /* (partially) satisfy request from storage */
  779. {
  780. unsigned char *src = s->s3->handshake_fragment;
  781. unsigned char *dst = buf;
  782. unsigned int k;
  783. /* peek == 0 */
  784. n = 0;
  785. while ((len > 0) && (s->s3->handshake_fragment_len > 0)) {
  786. *dst++ = *src++;
  787. len--;
  788. s->s3->handshake_fragment_len--;
  789. n++;
  790. }
  791. /* move any remaining fragment bytes: */
  792. for (k = 0; k < s->s3->handshake_fragment_len; k++)
  793. s->s3->handshake_fragment[k] = *src++;
  794. return n;
  795. }
  796. /*
  797. * Now s->s3->handshake_fragment_len == 0 if type == SSL3_RT_HANDSHAKE.
  798. */
  799. if (!s->in_handshake && SSL_in_init(s)) {
  800. /* type == SSL3_RT_APPLICATION_DATA */
  801. i = s->handshake_func(s);
  802. if (i < 0)
  803. return (i);
  804. if (i == 0) {
  805. SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE);
  806. return (-1);
  807. }
  808. }
  809. start:
  810. s->rwstate = SSL_NOTHING;
  811. /*-
  812. * s->s3->rrec.type - is the type of record
  813. * s->s3->rrec.data, - data
  814. * s->s3->rrec.off, - offset into 'data' for next read
  815. * s->s3->rrec.length, - number of bytes.
  816. */
  817. rr = &(s->s3->rrec);
  818. /* get new packet if necessary */
  819. if ((rr->length == 0) || (s->rstate == SSL_ST_READ_BODY)) {
  820. ret = ssl3_get_record(s);
  821. if (ret <= 0)
  822. return (ret);
  823. }
  824. /* we now have a packet which can be read and processed */
  825. if (s->s3->change_cipher_spec /* set when we receive ChangeCipherSpec,
  826. * reset by ssl3_get_finished */
  827. && (rr->type != SSL3_RT_HANDSHAKE)) {
  828. al = SSL_AD_UNEXPECTED_MESSAGE;
  829. SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_DATA_BETWEEN_CCS_AND_FINISHED);
  830. goto f_err;
  831. }
  832. /*
  833. * If the other end has shut down, throw anything we read away (even in
  834. * 'peek' mode)
  835. */
  836. if (s->shutdown & SSL_RECEIVED_SHUTDOWN) {
  837. rr->length = 0;
  838. s->rwstate = SSL_NOTHING;
  839. return (0);
  840. }
  841. if (type == rr->type) { /* SSL3_RT_APPLICATION_DATA or
  842. * SSL3_RT_HANDSHAKE */
  843. /*
  844. * make sure that we are not getting application data when we are
  845. * doing a handshake for the first time
  846. */
  847. if (SSL_in_init(s) && (type == SSL3_RT_APPLICATION_DATA) &&
  848. (s->enc_read_ctx == NULL)) {
  849. al = SSL_AD_UNEXPECTED_MESSAGE;
  850. SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_APP_DATA_IN_HANDSHAKE);
  851. goto f_err;
  852. }
  853. if (len <= 0)
  854. return (len);
  855. if ((unsigned int)len > rr->length)
  856. n = rr->length;
  857. else
  858. n = (unsigned int)len;
  859. memcpy(buf, &(rr->data[rr->off]), n);
  860. if (!peek) {
  861. rr->length -= n;
  862. rr->off += n;
  863. if (rr->length == 0) {
  864. s->rstate = SSL_ST_READ_HEADER;
  865. rr->off = 0;
  866. }
  867. }
  868. return (n);
  869. }
  870. /*
  871. * If we get here, then type != rr->type; if we have a handshake message,
  872. * then it was unexpected (Hello Request or Client Hello).
  873. */
  874. /*
  875. * In case of record types for which we have 'fragment' storage, fill
  876. * that so that we can process the data at a fixed place.
  877. */
  878. {
  879. unsigned int dest_maxlen = 0;
  880. unsigned char *dest = NULL;
  881. unsigned int *dest_len = NULL;
  882. if (rr->type == SSL3_RT_HANDSHAKE) {
  883. dest_maxlen = sizeof s->s3->handshake_fragment;
  884. dest = s->s3->handshake_fragment;
  885. dest_len = &s->s3->handshake_fragment_len;
  886. } else if (rr->type == SSL3_RT_ALERT) {
  887. dest_maxlen = sizeof s->s3->alert_fragment;
  888. dest = s->s3->alert_fragment;
  889. dest_len = &s->s3->alert_fragment_len;
  890. }
  891. if (dest_maxlen > 0) {
  892. n = dest_maxlen - *dest_len; /* available space in 'dest' */
  893. if (rr->length < n)
  894. n = rr->length; /* available bytes */
  895. /* now move 'n' bytes: */
  896. while (n-- > 0) {
  897. dest[(*dest_len)++] = rr->data[rr->off++];
  898. rr->length--;
  899. }
  900. if (*dest_len < dest_maxlen)
  901. goto start; /* fragment was too small */
  902. }
  903. }
  904. /*-
  905. * s->s3->handshake_fragment_len == 4 iff rr->type == SSL3_RT_HANDSHAKE;
  906. * s->s3->alert_fragment_len == 2 iff rr->type == SSL3_RT_ALERT.
  907. * (Possibly rr is 'empty' now, i.e. rr->length may be 0.)
  908. */
  909. /* If we are a client, check for an incoming 'Hello Request': */
  910. if ((!s->server) &&
  911. (s->s3->handshake_fragment_len >= 4) &&
  912. (s->s3->handshake_fragment[0] == SSL3_MT_HELLO_REQUEST) &&
  913. (s->session != NULL) && (s->session->cipher != NULL)) {
  914. s->s3->handshake_fragment_len = 0;
  915. if ((s->s3->handshake_fragment[1] != 0) ||
  916. (s->s3->handshake_fragment[2] != 0) ||
  917. (s->s3->handshake_fragment[3] != 0)) {
  918. al = SSL_AD_DECODE_ERROR;
  919. SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_BAD_HELLO_REQUEST);
  920. goto f_err;
  921. }
  922. if (s->msg_callback)
  923. s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
  924. s->s3->handshake_fragment, 4, s,
  925. s->msg_callback_arg);
  926. if (SSL_is_init_finished(s) &&
  927. !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS) &&
  928. !s->s3->renegotiate) {
  929. ssl3_renegotiate(s);
  930. if (ssl3_renegotiate_check(s)) {
  931. i = s->handshake_func(s);
  932. if (i < 0)
  933. return (i);
  934. if (i == 0) {
  935. SSLerr(SSL_F_SSL3_READ_BYTES,
  936. SSL_R_SSL_HANDSHAKE_FAILURE);
  937. return (-1);
  938. }
  939. if (!(s->mode & SSL_MODE_AUTO_RETRY)) {
  940. if (s->s3->rbuf.left == 0) { /* no read-ahead left? */
  941. BIO *bio;
  942. /*
  943. * In the case where we try to read application data,
  944. * but we trigger an SSL handshake, we return -1 with
  945. * the retry option set. Otherwise renegotiation may
  946. * cause nasty problems in the blocking world
  947. */
  948. s->rwstate = SSL_READING;
  949. bio = SSL_get_rbio(s);
  950. BIO_clear_retry_flags(bio);
  951. BIO_set_retry_read(bio);
  952. return (-1);
  953. }
  954. }
  955. }
  956. }
  957. /*
  958. * we either finished a handshake or ignored the request, now try
  959. * again to obtain the (application) data we were asked for
  960. */
  961. goto start;
  962. }
  963. /*
  964. * If we are a server and get a client hello when renegotiation isn't
  965. * allowed send back a no renegotiation alert and carry on. WARNING:
  966. * experimental code, needs reviewing (steve)
  967. */
  968. if (s->server &&
  969. SSL_is_init_finished(s) &&
  970. !s->s3->send_connection_binding &&
  971. (s->version > SSL3_VERSION) &&
  972. (s->s3->handshake_fragment_len >= 4) &&
  973. (s->s3->handshake_fragment[0] == SSL3_MT_CLIENT_HELLO) &&
  974. (s->session != NULL) && (s->session->cipher != NULL) &&
  975. !(s->ctx->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)) {
  976. /*
  977. * s->s3->handshake_fragment_len = 0;
  978. */
  979. rr->length = 0;
  980. ssl3_send_alert(s, SSL3_AL_WARNING, SSL_AD_NO_RENEGOTIATION);
  981. goto start;
  982. }
  983. if (s->s3->alert_fragment_len >= 2) {
  984. int alert_level = s->s3->alert_fragment[0];
  985. int alert_descr = s->s3->alert_fragment[1];
  986. s->s3->alert_fragment_len = 0;
  987. if (s->msg_callback)
  988. s->msg_callback(0, s->version, SSL3_RT_ALERT,
  989. s->s3->alert_fragment, 2, s, s->msg_callback_arg);
  990. if (s->info_callback != NULL)
  991. cb = s->info_callback;
  992. else if (s->ctx->info_callback != NULL)
  993. cb = s->ctx->info_callback;
  994. if (cb != NULL) {
  995. j = (alert_level << 8) | alert_descr;
  996. cb(s, SSL_CB_READ_ALERT, j);
  997. }
  998. if (alert_level == 1) { /* warning */
  999. s->s3->warn_alert = alert_descr;
  1000. if (alert_descr == SSL_AD_CLOSE_NOTIFY) {
  1001. s->shutdown |= SSL_RECEIVED_SHUTDOWN;
  1002. return (0);
  1003. }
  1004. /*
  1005. * This is a warning but we receive it if we requested
  1006. * renegotiation and the peer denied it. Terminate with a fatal
  1007. * alert because if application tried to renegotiatie it
  1008. * presumably had a good reason and expects it to succeed. In
  1009. * future we might have a renegotiation where we don't care if
  1010. * the peer refused it where we carry on.
  1011. */
  1012. else if (alert_descr == SSL_AD_NO_RENEGOTIATION) {
  1013. al = SSL_AD_HANDSHAKE_FAILURE;
  1014. SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_NO_RENEGOTIATION);
  1015. goto f_err;
  1016. }
  1017. } else if (alert_level == 2) { /* fatal */
  1018. char tmp[16];
  1019. s->rwstate = SSL_NOTHING;
  1020. s->s3->fatal_alert = alert_descr;
  1021. SSLerr(SSL_F_SSL3_READ_BYTES, SSL_AD_REASON_OFFSET + alert_descr);
  1022. BIO_snprintf(tmp, sizeof tmp, "%d", alert_descr);
  1023. ERR_add_error_data(2, "SSL alert number ", tmp);
  1024. s->shutdown |= SSL_RECEIVED_SHUTDOWN;
  1025. SSL_CTX_remove_session(s->ctx, s->session);
  1026. return (0);
  1027. } else {
  1028. al = SSL_AD_ILLEGAL_PARAMETER;
  1029. SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_UNKNOWN_ALERT_TYPE);
  1030. goto f_err;
  1031. }
  1032. goto start;
  1033. }
  1034. if (s->shutdown & SSL_SENT_SHUTDOWN) { /* but we have not received a
  1035. * shutdown */
  1036. s->rwstate = SSL_NOTHING;
  1037. rr->length = 0;
  1038. return (0);
  1039. }
  1040. if (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC) {
  1041. /*
  1042. * 'Change Cipher Spec' is just a single byte, so we know exactly
  1043. * what the record payload has to look like
  1044. */
  1045. if ((rr->length != 1) || (rr->off != 0) ||
  1046. (rr->data[0] != SSL3_MT_CCS)) {
  1047. al = SSL_AD_ILLEGAL_PARAMETER;
  1048. SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_BAD_CHANGE_CIPHER_SPEC);
  1049. goto f_err;
  1050. }
  1051. /* Check we have a cipher to change to */
  1052. if (s->s3->tmp.new_cipher == NULL) {
  1053. al = SSL_AD_UNEXPECTED_MESSAGE;
  1054. SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_CCS_RECEIVED_EARLY);
  1055. goto f_err;
  1056. }
  1057. if (!(s->s3->flags & SSL3_FLAGS_CCS_OK)) {
  1058. al = SSL_AD_UNEXPECTED_MESSAGE;
  1059. SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_CCS_RECEIVED_EARLY);
  1060. goto f_err;
  1061. }
  1062. s->s3->flags &= ~SSL3_FLAGS_CCS_OK;
  1063. rr->length = 0;
  1064. if (s->msg_callback)
  1065. s->msg_callback(0, s->version, SSL3_RT_CHANGE_CIPHER_SPEC,
  1066. rr->data, 1, s, s->msg_callback_arg);
  1067. s->s3->change_cipher_spec = 1;
  1068. if (!ssl3_do_change_cipher_spec(s))
  1069. goto err;
  1070. else
  1071. goto start;
  1072. }
  1073. /*
  1074. * Unexpected handshake message (Client Hello, or protocol violation)
  1075. */
  1076. if ((s->s3->handshake_fragment_len >= 4) && !s->in_handshake) {
  1077. if (((s->state & SSL_ST_MASK) == SSL_ST_OK) &&
  1078. !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS)) {
  1079. #if 0 /* worked only because C operator preferences
  1080. * are not as expected (and because this is
  1081. * not really needed for clients except for
  1082. * detecting protocol violations): */
  1083. s->state = SSL_ST_BEFORE | (s->server)
  1084. ? SSL_ST_ACCEPT : SSL_ST_CONNECT;
  1085. #else
  1086. s->state = s->server ? SSL_ST_ACCEPT : SSL_ST_CONNECT;
  1087. #endif
  1088. s->new_session = 1;
  1089. }
  1090. i = s->handshake_func(s);
  1091. if (i < 0)
  1092. return (i);
  1093. if (i == 0) {
  1094. SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE);
  1095. return (-1);
  1096. }
  1097. if (!(s->mode & SSL_MODE_AUTO_RETRY)) {
  1098. if (s->s3->rbuf.left == 0) { /* no read-ahead left? */
  1099. BIO *bio;
  1100. /*
  1101. * In the case where we try to read application data, but we
  1102. * trigger an SSL handshake, we return -1 with the retry
  1103. * option set. Otherwise renegotiation may cause nasty
  1104. * problems in the blocking world
  1105. */
  1106. s->rwstate = SSL_READING;
  1107. bio = SSL_get_rbio(s);
  1108. BIO_clear_retry_flags(bio);
  1109. BIO_set_retry_read(bio);
  1110. return (-1);
  1111. }
  1112. }
  1113. goto start;
  1114. }
  1115. switch (rr->type) {
  1116. default:
  1117. #ifndef OPENSSL_NO_TLS
  1118. /* TLS just ignores unknown message types */
  1119. if (s->version == TLS1_VERSION) {
  1120. rr->length = 0;
  1121. goto start;
  1122. }
  1123. #endif
  1124. al = SSL_AD_UNEXPECTED_MESSAGE;
  1125. SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_UNEXPECTED_RECORD);
  1126. goto f_err;
  1127. case SSL3_RT_CHANGE_CIPHER_SPEC:
  1128. case SSL3_RT_ALERT:
  1129. case SSL3_RT_HANDSHAKE:
  1130. /*
  1131. * we already handled all of these, with the possible exception of
  1132. * SSL3_RT_HANDSHAKE when s->in_handshake is set, but that should not
  1133. * happen when type != rr->type
  1134. */
  1135. al = SSL_AD_UNEXPECTED_MESSAGE;
  1136. SSLerr(SSL_F_SSL3_READ_BYTES, ERR_R_INTERNAL_ERROR);
  1137. goto f_err;
  1138. case SSL3_RT_APPLICATION_DATA:
  1139. /*
  1140. * At this point, we were expecting handshake data, but have
  1141. * application data. If the library was running inside ssl3_read()
  1142. * (i.e. in_read_app_data is set) and it makes sense to read
  1143. * application data at this point (session renegotiation not yet
  1144. * started), we will indulge it.
  1145. */
  1146. if (s->s3->in_read_app_data &&
  1147. (s->s3->total_renegotiations != 0) &&
  1148. (((s->state & SSL_ST_CONNECT) &&
  1149. (s->state >= SSL3_ST_CW_CLNT_HELLO_A) &&
  1150. (s->state <= SSL3_ST_CR_SRVR_HELLO_A)
  1151. ) || ((s->state & SSL_ST_ACCEPT) &&
  1152. (s->state <= SSL3_ST_SW_HELLO_REQ_A) &&
  1153. (s->state >= SSL3_ST_SR_CLNT_HELLO_A)
  1154. )
  1155. )) {
  1156. s->s3->in_read_app_data = 2;
  1157. return (-1);
  1158. } else {
  1159. al = SSL_AD_UNEXPECTED_MESSAGE;
  1160. SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_UNEXPECTED_RECORD);
  1161. goto f_err;
  1162. }
  1163. }
  1164. /* not reached */
  1165. f_err:
  1166. ssl3_send_alert(s, SSL3_AL_FATAL, al);
  1167. err:
  1168. return (-1);
  1169. }
  1170. int ssl3_do_change_cipher_spec(SSL *s)
  1171. {
  1172. int i;
  1173. const char *sender;
  1174. int slen;
  1175. if (s->state & SSL_ST_ACCEPT)
  1176. i = SSL3_CHANGE_CIPHER_SERVER_READ;
  1177. else
  1178. i = SSL3_CHANGE_CIPHER_CLIENT_READ;
  1179. if (s->s3->tmp.key_block == NULL) {
  1180. if (s->session == NULL || s->session->master_key_length == 0) {
  1181. /* might happen if dtls1_read_bytes() calls this */
  1182. SSLerr(SSL_F_SSL3_DO_CHANGE_CIPHER_SPEC,
  1183. SSL_R_CCS_RECEIVED_EARLY);
  1184. return (0);
  1185. }
  1186. s->session->cipher = s->s3->tmp.new_cipher;
  1187. if (!s->method->ssl3_enc->setup_key_block(s))
  1188. return (0);
  1189. }
  1190. if (!s->method->ssl3_enc->change_cipher_state(s, i))
  1191. return (0);
  1192. /*
  1193. * we have to record the message digest at this point so we can get it
  1194. * before we read the finished message
  1195. */
  1196. if (s->state & SSL_ST_CONNECT) {
  1197. sender = s->method->ssl3_enc->server_finished_label;
  1198. slen = s->method->ssl3_enc->server_finished_label_len;
  1199. } else {
  1200. sender = s->method->ssl3_enc->client_finished_label;
  1201. slen = s->method->ssl3_enc->client_finished_label_len;
  1202. }
  1203. s->s3->tmp.peer_finish_md_len = s->method->ssl3_enc->final_finish_mac(s,
  1204. &
  1205. (s->s3->finish_dgst1),
  1206. &
  1207. (s->s3->finish_dgst2),
  1208. sender,
  1209. slen,
  1210. s->s3->tmp.peer_finish_md);
  1211. return (1);
  1212. }
  1213. int ssl3_send_alert(SSL *s, int level, int desc)
  1214. {
  1215. /* Map tls/ssl alert value to correct one */
  1216. desc = s->method->ssl3_enc->alert_value(desc);
  1217. if (s->version == SSL3_VERSION && desc == SSL_AD_PROTOCOL_VERSION)
  1218. desc = SSL_AD_HANDSHAKE_FAILURE; /* SSL 3.0 does not have
  1219. * protocol_version alerts */
  1220. if (desc < 0)
  1221. return -1;
  1222. /* If a fatal one, remove from cache */
  1223. if ((level == 2) && (s->session != NULL))
  1224. SSL_CTX_remove_session(s->ctx, s->session);
  1225. s->s3->alert_dispatch = 1;
  1226. s->s3->send_alert[0] = level;
  1227. s->s3->send_alert[1] = desc;
  1228. if (s->s3->wbuf.left == 0) /* data still being written out? */
  1229. return s->method->ssl_dispatch_alert(s);
  1230. /*
  1231. * else data is still being written out, we will get written some time in
  1232. * the future
  1233. */
  1234. return -1;
  1235. }
  1236. int ssl3_dispatch_alert(SSL *s)
  1237. {
  1238. int i, j;
  1239. void (*cb) (const SSL *ssl, int type, int val) = NULL;
  1240. s->s3->alert_dispatch = 0;
  1241. i = do_ssl3_write(s, SSL3_RT_ALERT, &s->s3->send_alert[0], 2, 0);
  1242. if (i <= 0) {
  1243. s->s3->alert_dispatch = 1;
  1244. } else {
  1245. /*
  1246. * Alert sent to BIO. If it is important, flush it now. If the
  1247. * message does not get sent due to non-blocking IO, we will not
  1248. * worry too much.
  1249. */
  1250. if (s->s3->send_alert[0] == SSL3_AL_FATAL)
  1251. (void)BIO_flush(s->wbio);
  1252. if (s->msg_callback)
  1253. s->msg_callback(1, s->version, SSL3_RT_ALERT, s->s3->send_alert,
  1254. 2, s, s->msg_callback_arg);
  1255. if (s->info_callback != NULL)
  1256. cb = s->info_callback;
  1257. else if (s->ctx->info_callback != NULL)
  1258. cb = s->ctx->info_callback;
  1259. if (cb != NULL) {
  1260. j = (s->s3->send_alert[0] << 8) | s->s3->send_alert[1];
  1261. cb(s, SSL_CB_WRITE_ALERT, j);
  1262. }
  1263. }
  1264. return (i);
  1265. }