s3_pkt.c 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576
  1. /* ssl/s3_pkt.c */
  2. /* Copyright (C) 1995-1998 Eric Young ([email protected])
  3. * All rights reserved.
  4. *
  5. * This package is an SSL implementation written
  6. * by Eric Young ([email protected]).
  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 ([email protected]).
  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 ([email protected])"
  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 ([email protected])"
  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. * [email protected].
  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. * ([email protected]). This product includes software written by Tim
  108. * Hudson ([email protected]).
  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. #include <openssl/rand.h>
  119. static int do_ssl3_write(SSL *s, int type, const unsigned char *buf,
  120. unsigned int len, int create_empty_fragment);
  121. static int ssl3_get_record(SSL *s);
  122. int ssl3_read_n(SSL *s, int n, int max, int extend)
  123. {
  124. /*
  125. * If extend == 0, obtain new n-byte packet; if extend == 1, increase
  126. * packet by another n bytes. The packet will be in the sub-array of
  127. * s->s3->rbuf.buf specified by s->packet and s->packet_length. (If
  128. * s->read_ahead is set, 'max' bytes may be stored in rbuf [plus
  129. * s->packet_length bytes if extend == 1].)
  130. */
  131. int i, len, left;
  132. long align = 0;
  133. unsigned char *pkt;
  134. SSL3_BUFFER *rb;
  135. if (n <= 0)
  136. return n;
  137. rb = &(s->s3->rbuf);
  138. if (rb->buf == NULL)
  139. if (!ssl3_setup_read_buffer(s))
  140. return -1;
  141. left = rb->left;
  142. #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0
  143. align = (long)rb->buf + SSL3_RT_HEADER_LENGTH;
  144. align = (-align) & (SSL3_ALIGN_PAYLOAD - 1);
  145. #endif
  146. if (!extend) {
  147. /* start with empty packet ... */
  148. if (left == 0)
  149. rb->offset = align;
  150. else if (align != 0 && left >= SSL3_RT_HEADER_LENGTH) {
  151. /*
  152. * check if next packet length is large enough to justify payload
  153. * alignment...
  154. */
  155. pkt = rb->buf + rb->offset;
  156. if (pkt[0] == SSL3_RT_APPLICATION_DATA
  157. && (pkt[3] << 8 | pkt[4]) >= 128) {
  158. /*
  159. * Note that even if packet is corrupted and its length field
  160. * is insane, we can only be led to wrong decision about
  161. * whether memmove will occur or not. Header values has no
  162. * effect on memmove arguments and therefore no buffer
  163. * overrun can be triggered.
  164. */
  165. memmove(rb->buf + align, pkt, left);
  166. rb->offset = align;
  167. }
  168. }
  169. s->packet = rb->buf + rb->offset;
  170. s->packet_length = 0;
  171. /* ... now we can act as if 'extend' was set */
  172. }
  173. /*
  174. * For DTLS/UDP reads should not span multiple packets because the read
  175. * operation returns the whole packet at once (as long as it fits into
  176. * the buffer).
  177. */
  178. if (SSL_version(s) == DTLS1_VERSION || SSL_version(s) == DTLS1_BAD_VER) {
  179. if (left == 0 && extend)
  180. return 0;
  181. if (left > 0 && n > left)
  182. n = left;
  183. }
  184. /* if there is enough in the buffer from a previous read, take some */
  185. if (left >= n) {
  186. s->packet_length += n;
  187. rb->left = left - n;
  188. rb->offset += n;
  189. return (n);
  190. }
  191. /* else we need to read more data */
  192. len = s->packet_length;
  193. pkt = rb->buf + align;
  194. /*
  195. * Move any available bytes to front of buffer: 'len' bytes already
  196. * pointed to by 'packet', 'left' extra ones at the end
  197. */
  198. if (s->packet != pkt) { /* len > 0 */
  199. memmove(pkt, s->packet, len + left);
  200. s->packet = pkt;
  201. rb->offset = len + align;
  202. }
  203. if (n > (int)(rb->len - rb->offset)) { /* does not happen */
  204. SSLerr(SSL_F_SSL3_READ_N, ERR_R_INTERNAL_ERROR);
  205. return -1;
  206. }
  207. /* We always act like read_ahead is set for DTLS */
  208. if (!s->read_ahead && !SSL_IS_DTLS(s))
  209. /* ignore max parameter */
  210. max = n;
  211. else {
  212. if (max < n)
  213. max = n;
  214. if (max > (int)(rb->len - rb->offset))
  215. max = rb->len - rb->offset;
  216. }
  217. while (left < n) {
  218. /*
  219. * Now we have len+left bytes at the front of s->s3->rbuf.buf and
  220. * need to read in more until we have len+n (up to len+max if
  221. * possible)
  222. */
  223. clear_sys_error();
  224. if (s->rbio != NULL) {
  225. s->rwstate = SSL_READING;
  226. i = BIO_read(s->rbio, pkt + len + left, max - left);
  227. } else {
  228. SSLerr(SSL_F_SSL3_READ_N, SSL_R_READ_BIO_NOT_SET);
  229. i = -1;
  230. }
  231. if (i <= 0) {
  232. rb->left = left;
  233. if (s->mode & SSL_MODE_RELEASE_BUFFERS &&
  234. SSL_version(s) != DTLS1_VERSION
  235. && SSL_version(s) != DTLS1_BAD_VER)
  236. if (len + left == 0)
  237. ssl3_release_read_buffer(s);
  238. return (i);
  239. }
  240. left += i;
  241. /*
  242. * reads should *never* span multiple packets for DTLS because the
  243. * underlying transport protocol is message oriented as opposed to
  244. * byte oriented as in the TLS case.
  245. */
  246. if (SSL_version(s) == DTLS1_VERSION
  247. || SSL_version(s) == DTLS1_BAD_VER) {
  248. if (n > left)
  249. n = left; /* makes the while condition false */
  250. }
  251. }
  252. /* done reading, now the book-keeping */
  253. rb->offset += n;
  254. rb->left = left - n;
  255. s->packet_length += n;
  256. s->rwstate = SSL_NOTHING;
  257. return (n);
  258. }
  259. /*
  260. * MAX_EMPTY_RECORDS defines the number of consecutive, empty records that
  261. * will be processed per call to ssl3_get_record. Without this limit an
  262. * attacker could send empty records at a faster rate than we can process and
  263. * cause ssl3_get_record to loop forever.
  264. */
  265. #define MAX_EMPTY_RECORDS 32
  266. /*-
  267. * Call this to get a new input record.
  268. * It will return <= 0 if more data is needed, normally due to an error
  269. * or non-blocking IO.
  270. * When it finishes, one packet has been decoded and can be found in
  271. * ssl->s3->rrec.type - is the type of record
  272. * ssl->s3->rrec.data, - data
  273. * ssl->s3->rrec.length, - number of bytes
  274. */
  275. /* used only by ssl3_read_bytes */
  276. static int ssl3_get_record(SSL *s)
  277. {
  278. int ssl_major, ssl_minor, al;
  279. int enc_err, n, i, ret = -1;
  280. SSL3_RECORD *rr;
  281. SSL_SESSION *sess;
  282. unsigned char *p;
  283. unsigned char md[EVP_MAX_MD_SIZE];
  284. short version;
  285. unsigned mac_size, orig_len;
  286. size_t extra;
  287. unsigned empty_record_count = 0;
  288. rr = &(s->s3->rrec);
  289. sess = s->session;
  290. if (s->options & SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER)
  291. extra = SSL3_RT_MAX_EXTRA;
  292. else
  293. extra = 0;
  294. if (extra && !s->s3->init_extra) {
  295. /*
  296. * An application error: SLS_OP_MICROSOFT_BIG_SSLV3_BUFFER set after
  297. * ssl3_setup_buffers() was done
  298. */
  299. SSLerr(SSL_F_SSL3_GET_RECORD, ERR_R_INTERNAL_ERROR);
  300. return -1;
  301. }
  302. again:
  303. /* check if we have the header */
  304. if ((s->rstate != SSL_ST_READ_BODY) ||
  305. (s->packet_length < SSL3_RT_HEADER_LENGTH)) {
  306. n = ssl3_read_n(s, SSL3_RT_HEADER_LENGTH, s->s3->rbuf.len, 0);
  307. if (n <= 0)
  308. return (n); /* error or non-blocking */
  309. s->rstate = SSL_ST_READ_BODY;
  310. p = s->packet;
  311. /* Pull apart the header into the SSL3_RECORD */
  312. rr->type = *(p++);
  313. ssl_major = *(p++);
  314. ssl_minor = *(p++);
  315. version = (ssl_major << 8) | ssl_minor;
  316. n2s(p, rr->length);
  317. #if 0
  318. fprintf(stderr, "Record type=%d, Length=%d\n", rr->type, rr->length);
  319. #endif
  320. /* Lets check version */
  321. if (!s->first_packet) {
  322. if (version != s->version) {
  323. SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_WRONG_VERSION_NUMBER);
  324. if ((s->version & 0xFF00) == (version & 0xFF00)
  325. && !s->enc_write_ctx && !s->write_hash) {
  326. if (rr->type == SSL3_RT_ALERT) {
  327. /*
  328. * The record is using an incorrect version number, but
  329. * what we've got appears to be an alert. We haven't
  330. * read the body yet to check whether its a fatal or
  331. * not - but chances are it is. We probably shouldn't
  332. * send a fatal alert back. We'll just end.
  333. */
  334. goto err;
  335. }
  336. /*
  337. * Send back error using their minor version number :-)
  338. */
  339. s->version = (unsigned short)version;
  340. }
  341. al = SSL_AD_PROTOCOL_VERSION;
  342. goto f_err;
  343. }
  344. }
  345. if ((version >> 8) != SSL3_VERSION_MAJOR) {
  346. SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_WRONG_VERSION_NUMBER);
  347. goto err;
  348. }
  349. if (rr->length > s->s3->rbuf.len - SSL3_RT_HEADER_LENGTH) {
  350. al = SSL_AD_RECORD_OVERFLOW;
  351. SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_PACKET_LENGTH_TOO_LONG);
  352. goto f_err;
  353. }
  354. /* now s->rstate == SSL_ST_READ_BODY */
  355. }
  356. /* s->rstate == SSL_ST_READ_BODY, get and decode the data */
  357. if (rr->length > s->packet_length - SSL3_RT_HEADER_LENGTH) {
  358. /* now s->packet_length == SSL3_RT_HEADER_LENGTH */
  359. i = rr->length;
  360. n = ssl3_read_n(s, i, i, 1);
  361. if (n <= 0)
  362. return (n); /* error or non-blocking io */
  363. /*
  364. * now n == rr->length, and s->packet_length == SSL3_RT_HEADER_LENGTH
  365. * + rr->length
  366. */
  367. }
  368. s->rstate = SSL_ST_READ_HEADER; /* set state for later operations */
  369. /*
  370. * At this point, s->packet_length == SSL3_RT_HEADER_LNGTH + rr->length,
  371. * and we have that many bytes in s->packet
  372. */
  373. rr->input = &(s->packet[SSL3_RT_HEADER_LENGTH]);
  374. /*
  375. * ok, we can now read from 's->packet' data into 'rr' rr->input points
  376. * at rr->length bytes, which need to be copied into rr->data by either
  377. * the decryption or by the decompression When the data is 'copied' into
  378. * the rr->data buffer, rr->input will be pointed at the new buffer
  379. */
  380. /*
  381. * We now have - encrypted [ MAC [ compressed [ plain ] ] ] rr->length
  382. * bytes of encrypted compressed stuff.
  383. */
  384. /* check is not needed I believe */
  385. if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH + extra) {
  386. al = SSL_AD_RECORD_OVERFLOW;
  387. SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
  388. goto f_err;
  389. }
  390. /* decrypt in place in 'rr->input' */
  391. rr->data = rr->input;
  392. enc_err = s->method->ssl3_enc->enc(s, 0);
  393. /*-
  394. * enc_err is:
  395. * 0: (in non-constant time) if the record is publically invalid.
  396. * 1: if the padding is valid
  397. * -1: if the padding is invalid
  398. */
  399. if (enc_err == 0) {
  400. al = SSL_AD_DECRYPTION_FAILED;
  401. SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_BLOCK_CIPHER_PAD_IS_WRONG);
  402. goto f_err;
  403. }
  404. #ifdef TLS_DEBUG
  405. printf("dec %d\n", rr->length);
  406. {
  407. unsigned int z;
  408. for (z = 0; z < rr->length; z++)
  409. printf("%02X%c", rr->data[z], ((z + 1) % 16) ? ' ' : '\n');
  410. }
  411. printf("\n");
  412. #endif
  413. /* r->length is now the compressed data plus mac */
  414. if ((sess != NULL) &&
  415. (s->enc_read_ctx != NULL) && (EVP_MD_CTX_md(s->read_hash) != NULL)) {
  416. /* s->read_hash != NULL => mac_size != -1 */
  417. unsigned char *mac = NULL;
  418. unsigned char mac_tmp[EVP_MAX_MD_SIZE];
  419. mac_size = EVP_MD_CTX_size(s->read_hash);
  420. OPENSSL_assert(mac_size <= EVP_MAX_MD_SIZE);
  421. /*
  422. * kludge: *_cbc_remove_padding passes padding length in rr->type
  423. */
  424. orig_len = rr->length + ((unsigned int)rr->type >> 8);
  425. /*
  426. * orig_len is the length of the record before any padding was
  427. * removed. This is public information, as is the MAC in use,
  428. * therefore we can safely process the record in a different amount
  429. * of time if it's too short to possibly contain a MAC.
  430. */
  431. if (orig_len < mac_size ||
  432. /* CBC records must have a padding length byte too. */
  433. (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
  434. orig_len < mac_size + 1)) {
  435. al = SSL_AD_DECODE_ERROR;
  436. SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_LENGTH_TOO_SHORT);
  437. goto f_err;
  438. }
  439. if (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE) {
  440. /*
  441. * We update the length so that the TLS header bytes can be
  442. * constructed correctly but we need to extract the MAC in
  443. * constant time from within the record, without leaking the
  444. * contents of the padding bytes.
  445. */
  446. mac = mac_tmp;
  447. ssl3_cbc_copy_mac(mac_tmp, rr, mac_size, orig_len);
  448. rr->length -= mac_size;
  449. } else {
  450. /*
  451. * In this case there's no padding, so |orig_len| equals
  452. * |rec->length| and we checked that there's enough bytes for
  453. * |mac_size| above.
  454. */
  455. rr->length -= mac_size;
  456. mac = &rr->data[rr->length];
  457. }
  458. i = s->method->ssl3_enc->mac(s, md, 0 /* not send */ );
  459. if (i < 0 || mac == NULL
  460. || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0)
  461. enc_err = -1;
  462. if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH + extra + mac_size)
  463. enc_err = -1;
  464. }
  465. if (enc_err < 0) {
  466. /*
  467. * A separate 'decryption_failed' alert was introduced with TLS 1.0,
  468. * SSL 3.0 only has 'bad_record_mac'. But unless a decryption
  469. * failure is directly visible from the ciphertext anyway, we should
  470. * not reveal which kind of error occured -- this might become
  471. * visible to an attacker (e.g. via a logfile)
  472. */
  473. al = SSL_AD_BAD_RECORD_MAC;
  474. SSLerr(SSL_F_SSL3_GET_RECORD,
  475. SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
  476. goto f_err;
  477. }
  478. /* r->length is now just compressed */
  479. if (s->expand != NULL) {
  480. if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH + extra) {
  481. al = SSL_AD_RECORD_OVERFLOW;
  482. SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_COMPRESSED_LENGTH_TOO_LONG);
  483. goto f_err;
  484. }
  485. if (!ssl3_do_uncompress(s)) {
  486. al = SSL_AD_DECOMPRESSION_FAILURE;
  487. SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_BAD_DECOMPRESSION);
  488. goto f_err;
  489. }
  490. }
  491. if (rr->length > SSL3_RT_MAX_PLAIN_LENGTH + extra) {
  492. al = SSL_AD_RECORD_OVERFLOW;
  493. SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_DATA_LENGTH_TOO_LONG);
  494. goto f_err;
  495. }
  496. rr->off = 0;
  497. /*-
  498. * So at this point the following is true
  499. * ssl->s3->rrec.type is the type of record
  500. * ssl->s3->rrec.length == number of bytes in record
  501. * ssl->s3->rrec.off == offset to first valid byte
  502. * ssl->s3->rrec.data == where to take bytes from, increment
  503. * after use :-).
  504. */
  505. /* we have pulled in a full packet so zero things */
  506. s->packet_length = 0;
  507. /* just read a 0 length packet */
  508. if (rr->length == 0) {
  509. empty_record_count++;
  510. if (empty_record_count > MAX_EMPTY_RECORDS) {
  511. al = SSL_AD_UNEXPECTED_MESSAGE;
  512. SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_RECORD_TOO_SMALL);
  513. goto f_err;
  514. }
  515. goto again;
  516. }
  517. #if 0
  518. fprintf(stderr, "Ultimate Record type=%d, Length=%d\n", rr->type,
  519. rr->length);
  520. #endif
  521. return (1);
  522. f_err:
  523. ssl3_send_alert(s, SSL3_AL_FATAL, al);
  524. err:
  525. return (ret);
  526. }
  527. int ssl3_do_uncompress(SSL *ssl)
  528. {
  529. #ifndef OPENSSL_NO_COMP
  530. int i;
  531. SSL3_RECORD *rr;
  532. rr = &(ssl->s3->rrec);
  533. i = COMP_expand_block(ssl->expand, rr->comp,
  534. SSL3_RT_MAX_PLAIN_LENGTH, rr->data,
  535. (int)rr->length);
  536. if (i < 0)
  537. return (0);
  538. else
  539. rr->length = i;
  540. rr->data = rr->comp;
  541. #endif
  542. return (1);
  543. }
  544. int ssl3_do_compress(SSL *ssl)
  545. {
  546. #ifndef OPENSSL_NO_COMP
  547. int i;
  548. SSL3_RECORD *wr;
  549. wr = &(ssl->s3->wrec);
  550. i = COMP_compress_block(ssl->compress, wr->data,
  551. SSL3_RT_MAX_COMPRESSED_LENGTH,
  552. wr->input, (int)wr->length);
  553. if (i < 0)
  554. return (0);
  555. else
  556. wr->length = i;
  557. wr->input = wr->data;
  558. #endif
  559. return (1);
  560. }
  561. /*
  562. * Call this to write data in records of type 'type' It will return <= 0 if
  563. * not all data has been sent or non-blocking IO.
  564. */
  565. int ssl3_write_bytes(SSL *s, int type, const void *buf_, int len)
  566. {
  567. const unsigned char *buf = buf_;
  568. unsigned int n, nw;
  569. int i, tot;
  570. s->rwstate = SSL_NOTHING;
  571. OPENSSL_assert(s->s3->wnum <= INT_MAX);
  572. tot = s->s3->wnum;
  573. s->s3->wnum = 0;
  574. if (SSL_in_init(s) && !s->in_handshake) {
  575. i = s->handshake_func(s);
  576. if (i < 0)
  577. return (i);
  578. if (i == 0) {
  579. SSLerr(SSL_F_SSL3_WRITE_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE);
  580. return -1;
  581. }
  582. }
  583. /*
  584. * ensure that if we end up with a smaller value of data to write out
  585. * than the the original len from a write which didn't complete for
  586. * non-blocking I/O and also somehow ended up avoiding the check for
  587. * this in ssl3_write_pending/SSL_R_BAD_WRITE_RETRY as it must never be
  588. * possible to end up with (len-tot) as a large number that will then
  589. * promptly send beyond the end of the users buffer ... so we trap and
  590. * report the error in a way the user will notice
  591. */
  592. if (len < tot) {
  593. SSLerr(SSL_F_SSL3_WRITE_BYTES, SSL_R_BAD_LENGTH);
  594. return (-1);
  595. }
  596. n = (len - tot);
  597. for (;;) {
  598. if (n > s->max_send_fragment)
  599. nw = s->max_send_fragment;
  600. else
  601. nw = n;
  602. i = do_ssl3_write(s, type, &(buf[tot]), nw, 0);
  603. if (i <= 0) {
  604. s->s3->wnum = tot;
  605. return i;
  606. }
  607. if ((i == (int)n) ||
  608. (type == SSL3_RT_APPLICATION_DATA &&
  609. (s->mode & SSL_MODE_ENABLE_PARTIAL_WRITE))) {
  610. /*
  611. * next chunk of data should get another prepended empty fragment
  612. * in ciphersuites with known-IV weakness:
  613. */
  614. s->s3->empty_fragment_done = 0;
  615. return tot + i;
  616. }
  617. n -= i;
  618. tot += i;
  619. }
  620. }
  621. static int do_ssl3_write(SSL *s, int type, const unsigned char *buf,
  622. unsigned int len, int create_empty_fragment)
  623. {
  624. unsigned char *p, *plen;
  625. int i, mac_size, clear = 0;
  626. int prefix_len = 0;
  627. int eivlen;
  628. long align = 0;
  629. SSL3_RECORD *wr;
  630. SSL3_BUFFER *wb = &(s->s3->wbuf);
  631. SSL_SESSION *sess;
  632. /*
  633. * first check if there is a SSL3_BUFFER still being written out. This
  634. * will happen with non blocking IO
  635. */
  636. if (wb->left != 0)
  637. return (ssl3_write_pending(s, type, buf, len));
  638. /* If we have an alert to send, lets send it */
  639. if (s->s3->alert_dispatch) {
  640. i = s->method->ssl_dispatch_alert(s);
  641. if (i <= 0)
  642. return (i);
  643. /* if it went, fall through and send more stuff */
  644. }
  645. if (wb->buf == NULL)
  646. if (!ssl3_setup_write_buffer(s))
  647. return -1;
  648. if (len == 0 && !create_empty_fragment)
  649. return 0;
  650. wr = &(s->s3->wrec);
  651. sess = s->session;
  652. if ((sess == NULL) ||
  653. (s->enc_write_ctx == NULL) ||
  654. (EVP_MD_CTX_md(s->write_hash) == NULL)) {
  655. #if 1
  656. clear = s->enc_write_ctx ? 0 : 1; /* must be AEAD cipher */
  657. #else
  658. clear = 1;
  659. #endif
  660. mac_size = 0;
  661. } else {
  662. mac_size = EVP_MD_CTX_size(s->write_hash);
  663. if (mac_size < 0)
  664. goto err;
  665. }
  666. /*
  667. * 'create_empty_fragment' is true only when this function calls itself
  668. */
  669. if (!clear && !create_empty_fragment && !s->s3->empty_fragment_done) {
  670. /*
  671. * countermeasure against known-IV weakness in CBC ciphersuites (see
  672. * http://www.openssl.org/~bodo/tls-cbc.txt)
  673. */
  674. if (s->s3->need_empty_fragments && type == SSL3_RT_APPLICATION_DATA) {
  675. /*
  676. * recursive function call with 'create_empty_fragment' set; this
  677. * prepares and buffers the data for an empty fragment (these
  678. * 'prefix_len' bytes are sent out later together with the actual
  679. * payload)
  680. */
  681. prefix_len = do_ssl3_write(s, type, buf, 0, 1);
  682. if (prefix_len <= 0)
  683. goto err;
  684. if (prefix_len >
  685. (SSL3_RT_HEADER_LENGTH + SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD))
  686. {
  687. /* insufficient space */
  688. SSLerr(SSL_F_DO_SSL3_WRITE, ERR_R_INTERNAL_ERROR);
  689. goto err;
  690. }
  691. }
  692. s->s3->empty_fragment_done = 1;
  693. }
  694. if (create_empty_fragment) {
  695. #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0
  696. /*
  697. * extra fragment would be couple of cipher blocks, which would be
  698. * multiple of SSL3_ALIGN_PAYLOAD, so if we want to align the real
  699. * payload, then we can just pretent we simply have two headers.
  700. */
  701. align = (long)wb->buf + 2 * SSL3_RT_HEADER_LENGTH;
  702. align = (-align) & (SSL3_ALIGN_PAYLOAD - 1);
  703. #endif
  704. p = wb->buf + align;
  705. wb->offset = align;
  706. } else if (prefix_len) {
  707. p = wb->buf + wb->offset + prefix_len;
  708. } else {
  709. #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0
  710. align = (long)wb->buf + SSL3_RT_HEADER_LENGTH;
  711. align = (-align) & (SSL3_ALIGN_PAYLOAD - 1);
  712. #endif
  713. p = wb->buf + align;
  714. wb->offset = align;
  715. }
  716. /* write the header */
  717. *(p++) = type & 0xff;
  718. wr->type = type;
  719. *(p++) = (s->version >> 8);
  720. /*
  721. * Some servers hang if iniatial client hello is larger than 256 bytes
  722. * and record version number > TLS 1.0
  723. */
  724. if (s->state == SSL3_ST_CW_CLNT_HELLO_B
  725. && !s->renegotiate && TLS1_get_version(s) > TLS1_VERSION)
  726. *(p++) = 0x1;
  727. else
  728. *(p++) = s->version & 0xff;
  729. /* field where we are to write out packet length */
  730. plen = p;
  731. p += 2;
  732. /* Explicit IV length, block ciphers and TLS version 1.1 or later */
  733. if (s->enc_write_ctx && s->version >= TLS1_1_VERSION) {
  734. int mode = EVP_CIPHER_CTX_mode(s->enc_write_ctx);
  735. if (mode == EVP_CIPH_CBC_MODE) {
  736. eivlen = EVP_CIPHER_CTX_iv_length(s->enc_write_ctx);
  737. if (eivlen <= 1)
  738. eivlen = 0;
  739. }
  740. /* Need explicit part of IV for GCM mode */
  741. else if (mode == EVP_CIPH_GCM_MODE)
  742. eivlen = EVP_GCM_TLS_EXPLICIT_IV_LEN;
  743. else
  744. eivlen = 0;
  745. } else
  746. eivlen = 0;
  747. /* lets setup the record stuff. */
  748. wr->data = p + eivlen;
  749. wr->length = (int)len;
  750. wr->input = (unsigned char *)buf;
  751. /*
  752. * we now 'read' from wr->input, wr->length bytes into wr->data
  753. */
  754. /* first we compress */
  755. if (s->compress != NULL) {
  756. if (!ssl3_do_compress(s)) {
  757. SSLerr(SSL_F_DO_SSL3_WRITE, SSL_R_COMPRESSION_FAILURE);
  758. goto err;
  759. }
  760. } else {
  761. memcpy(wr->data, wr->input, wr->length);
  762. wr->input = wr->data;
  763. }
  764. /*
  765. * we should still have the output to wr->data and the input from
  766. * wr->input. Length should be wr->length. wr->data still points in the
  767. * wb->buf
  768. */
  769. if (mac_size != 0) {
  770. if (s->method->ssl3_enc->mac(s, &(p[wr->length + eivlen]), 1) < 0)
  771. goto err;
  772. wr->length += mac_size;
  773. }
  774. wr->input = p;
  775. wr->data = p;
  776. if (eivlen) {
  777. /*
  778. * if (RAND_pseudo_bytes(p, eivlen) <= 0) goto err;
  779. */
  780. wr->length += eivlen;
  781. }
  782. if (s->method->ssl3_enc->enc(s, 1) < 1)
  783. goto err;
  784. /* record length after mac and block padding */
  785. s2n(wr->length, plen);
  786. /*
  787. * we should now have wr->data pointing to the encrypted data, which is
  788. * wr->length long
  789. */
  790. wr->type = type; /* not needed but helps for debugging */
  791. wr->length += SSL3_RT_HEADER_LENGTH;
  792. if (create_empty_fragment) {
  793. /*
  794. * we are in a recursive call; just return the length, don't write
  795. * out anything here
  796. */
  797. return wr->length;
  798. }
  799. /* now let's set up wb */
  800. wb->left = prefix_len + wr->length;
  801. /*
  802. * memorize arguments so that ssl3_write_pending can detect bad write
  803. * retries later
  804. */
  805. s->s3->wpend_tot = len;
  806. s->s3->wpend_buf = buf;
  807. s->s3->wpend_type = type;
  808. s->s3->wpend_ret = len;
  809. /* we now just need to write the buffer */
  810. return ssl3_write_pending(s, type, buf, len);
  811. err:
  812. return -1;
  813. }
  814. /* if s->s3->wbuf.left != 0, we need to call this */
  815. int ssl3_write_pending(SSL *s, int type, const unsigned char *buf,
  816. unsigned int len)
  817. {
  818. int i;
  819. SSL3_BUFFER *wb = &(s->s3->wbuf);
  820. /* XXXX */
  821. if ((s->s3->wpend_tot > (int)len)
  822. || ((s->s3->wpend_buf != buf) &&
  823. !(s->mode & SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER))
  824. || (s->s3->wpend_type != type)) {
  825. SSLerr(SSL_F_SSL3_WRITE_PENDING, SSL_R_BAD_WRITE_RETRY);
  826. return (-1);
  827. }
  828. for (;;) {
  829. clear_sys_error();
  830. if (s->wbio != NULL) {
  831. s->rwstate = SSL_WRITING;
  832. i = BIO_write(s->wbio,
  833. (char *)&(wb->buf[wb->offset]),
  834. (unsigned int)wb->left);
  835. } else {
  836. SSLerr(SSL_F_SSL3_WRITE_PENDING, SSL_R_BIO_NOT_SET);
  837. i = -1;
  838. }
  839. if (i == wb->left) {
  840. wb->left = 0;
  841. wb->offset += i;
  842. if (s->mode & SSL_MODE_RELEASE_BUFFERS &&
  843. SSL_version(s) != DTLS1_VERSION
  844. && SSL_version(s) != DTLS1_BAD_VER)
  845. ssl3_release_write_buffer(s);
  846. s->rwstate = SSL_NOTHING;
  847. return (s->s3->wpend_ret);
  848. } else if (i <= 0) {
  849. if (s->version == DTLS1_VERSION || s->version == DTLS1_BAD_VER) {
  850. /*
  851. * For DTLS, just drop it. That's kind of the whole point in
  852. * using a datagram service
  853. */
  854. wb->left = 0;
  855. }
  856. return (i);
  857. }
  858. wb->offset += i;
  859. wb->left -= i;
  860. }
  861. }
  862. /*-
  863. * Return up to 'len' payload bytes received in 'type' records.
  864. * 'type' is one of the following:
  865. *
  866. * - SSL3_RT_HANDSHAKE (when ssl3_get_message calls us)
  867. * - SSL3_RT_APPLICATION_DATA (when ssl3_read calls us)
  868. * - 0 (during a shutdown, no data has to be returned)
  869. *
  870. * If we don't have stored data to work from, read a SSL/TLS record first
  871. * (possibly multiple records if we still don't have anything to return).
  872. *
  873. * This function must handle any surprises the peer may have for us, such as
  874. * Alert records (e.g. close_notify), ChangeCipherSpec records (not really
  875. * a surprise, but handled as if it were), or renegotiation requests.
  876. * Also if record payloads contain fragments too small to process, we store
  877. * them until there is enough for the respective protocol (the record protocol
  878. * may use arbitrary fragmentation and even interleaving):
  879. * Change cipher spec protocol
  880. * just 1 byte needed, no need for keeping anything stored
  881. * Alert protocol
  882. * 2 bytes needed (AlertLevel, AlertDescription)
  883. * Handshake protocol
  884. * 4 bytes needed (HandshakeType, uint24 length) -- we just have
  885. * to detect unexpected Client Hello and Hello Request messages
  886. * here, anything else is handled by higher layers
  887. * Application data protocol
  888. * none of our business
  889. */
  890. int ssl3_read_bytes(SSL *s, int type, unsigned char *buf, int len, int peek)
  891. {
  892. int al, i, j, ret;
  893. unsigned int n;
  894. SSL3_RECORD *rr;
  895. void (*cb) (const SSL *ssl, int type2, int val) = NULL;
  896. if (s->s3->rbuf.buf == NULL) /* Not initialized yet */
  897. if (!ssl3_setup_read_buffer(s))
  898. return (-1);
  899. if ((type && (type != SSL3_RT_APPLICATION_DATA)
  900. && (type != SSL3_RT_HANDSHAKE)) || (peek
  901. && (type !=
  902. SSL3_RT_APPLICATION_DATA))) {
  903. SSLerr(SSL_F_SSL3_READ_BYTES, ERR_R_INTERNAL_ERROR);
  904. return -1;
  905. }
  906. if ((type == SSL3_RT_HANDSHAKE) && (s->s3->handshake_fragment_len > 0))
  907. /* (partially) satisfy request from storage */
  908. {
  909. unsigned char *src = s->s3->handshake_fragment;
  910. unsigned char *dst = buf;
  911. unsigned int k;
  912. /* peek == 0 */
  913. n = 0;
  914. while ((len > 0) && (s->s3->handshake_fragment_len > 0)) {
  915. *dst++ = *src++;
  916. len--;
  917. s->s3->handshake_fragment_len--;
  918. n++;
  919. }
  920. /* move any remaining fragment bytes: */
  921. for (k = 0; k < s->s3->handshake_fragment_len; k++)
  922. s->s3->handshake_fragment[k] = *src++;
  923. return n;
  924. }
  925. /*
  926. * Now s->s3->handshake_fragment_len == 0 if type == SSL3_RT_HANDSHAKE.
  927. */
  928. if (!s->in_handshake && SSL_in_init(s)) {
  929. /* type == SSL3_RT_APPLICATION_DATA */
  930. i = s->handshake_func(s);
  931. if (i < 0)
  932. return (i);
  933. if (i == 0) {
  934. SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE);
  935. return (-1);
  936. }
  937. }
  938. start:
  939. s->rwstate = SSL_NOTHING;
  940. /*-
  941. * s->s3->rrec.type - is the type of record
  942. * s->s3->rrec.data, - data
  943. * s->s3->rrec.off, - offset into 'data' for next read
  944. * s->s3->rrec.length, - number of bytes.
  945. */
  946. rr = &(s->s3->rrec);
  947. /* get new packet if necessary */
  948. if ((rr->length == 0) || (s->rstate == SSL_ST_READ_BODY)) {
  949. ret = ssl3_get_record(s);
  950. if (ret <= 0)
  951. return (ret);
  952. }
  953. /* we now have a packet which can be read and processed */
  954. if (s->s3->change_cipher_spec /* set when we receive ChangeCipherSpec,
  955. * reset by ssl3_get_finished */
  956. && (rr->type != SSL3_RT_HANDSHAKE)) {
  957. al = SSL_AD_UNEXPECTED_MESSAGE;
  958. SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_DATA_BETWEEN_CCS_AND_FINISHED);
  959. goto f_err;
  960. }
  961. /*
  962. * If the other end has shut down, throw anything we read away (even in
  963. * 'peek' mode)
  964. */
  965. if (s->shutdown & SSL_RECEIVED_SHUTDOWN) {
  966. rr->length = 0;
  967. s->rwstate = SSL_NOTHING;
  968. return (0);
  969. }
  970. if (type == rr->type) { /* SSL3_RT_APPLICATION_DATA or
  971. * SSL3_RT_HANDSHAKE */
  972. /*
  973. * make sure that we are not getting application data when we are
  974. * doing a handshake for the first time
  975. */
  976. if (SSL_in_init(s) && (type == SSL3_RT_APPLICATION_DATA) &&
  977. (s->enc_read_ctx == NULL)) {
  978. al = SSL_AD_UNEXPECTED_MESSAGE;
  979. SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_APP_DATA_IN_HANDSHAKE);
  980. goto f_err;
  981. }
  982. if (len <= 0)
  983. return (len);
  984. if ((unsigned int)len > rr->length)
  985. n = rr->length;
  986. else
  987. n = (unsigned int)len;
  988. memcpy(buf, &(rr->data[rr->off]), n);
  989. if (!peek) {
  990. rr->length -= n;
  991. rr->off += n;
  992. if (rr->length == 0) {
  993. s->rstate = SSL_ST_READ_HEADER;
  994. rr->off = 0;
  995. if (s->mode & SSL_MODE_RELEASE_BUFFERS
  996. && s->s3->rbuf.left == 0)
  997. ssl3_release_read_buffer(s);
  998. }
  999. }
  1000. return (n);
  1001. }
  1002. /*
  1003. * If we get here, then type != rr->type; if we have a handshake message,
  1004. * then it was unexpected (Hello Request or Client Hello).
  1005. */
  1006. /*
  1007. * In case of record types for which we have 'fragment' storage, fill
  1008. * that so that we can process the data at a fixed place.
  1009. */
  1010. {
  1011. unsigned int dest_maxlen = 0;
  1012. unsigned char *dest = NULL;
  1013. unsigned int *dest_len = NULL;
  1014. if (rr->type == SSL3_RT_HANDSHAKE) {
  1015. dest_maxlen = sizeof s->s3->handshake_fragment;
  1016. dest = s->s3->handshake_fragment;
  1017. dest_len = &s->s3->handshake_fragment_len;
  1018. } else if (rr->type == SSL3_RT_ALERT) {
  1019. dest_maxlen = sizeof s->s3->alert_fragment;
  1020. dest = s->s3->alert_fragment;
  1021. dest_len = &s->s3->alert_fragment_len;
  1022. }
  1023. #ifndef OPENSSL_NO_HEARTBEATS
  1024. else if (rr->type == TLS1_RT_HEARTBEAT) {
  1025. tls1_process_heartbeat(s);
  1026. /* Exit and notify application to read again */
  1027. rr->length = 0;
  1028. s->rwstate = SSL_READING;
  1029. BIO_clear_retry_flags(SSL_get_rbio(s));
  1030. BIO_set_retry_read(SSL_get_rbio(s));
  1031. return (-1);
  1032. }
  1033. #endif
  1034. if (dest_maxlen > 0) {
  1035. n = dest_maxlen - *dest_len; /* available space in 'dest' */
  1036. if (rr->length < n)
  1037. n = rr->length; /* available bytes */
  1038. /* now move 'n' bytes: */
  1039. while (n-- > 0) {
  1040. dest[(*dest_len)++] = rr->data[rr->off++];
  1041. rr->length--;
  1042. }
  1043. if (*dest_len < dest_maxlen)
  1044. goto start; /* fragment was too small */
  1045. }
  1046. }
  1047. /*-
  1048. * s->s3->handshake_fragment_len == 4 iff rr->type == SSL3_RT_HANDSHAKE;
  1049. * s->s3->alert_fragment_len == 2 iff rr->type == SSL3_RT_ALERT.
  1050. * (Possibly rr is 'empty' now, i.e. rr->length may be 0.)
  1051. */
  1052. /* If we are a client, check for an incoming 'Hello Request': */
  1053. if ((!s->server) &&
  1054. (s->s3->handshake_fragment_len >= 4) &&
  1055. (s->s3->handshake_fragment[0] == SSL3_MT_HELLO_REQUEST) &&
  1056. (s->session != NULL) && (s->session->cipher != NULL)) {
  1057. s->s3->handshake_fragment_len = 0;
  1058. if ((s->s3->handshake_fragment[1] != 0) ||
  1059. (s->s3->handshake_fragment[2] != 0) ||
  1060. (s->s3->handshake_fragment[3] != 0)) {
  1061. al = SSL_AD_DECODE_ERROR;
  1062. SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_BAD_HELLO_REQUEST);
  1063. goto f_err;
  1064. }
  1065. if (s->msg_callback)
  1066. s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
  1067. s->s3->handshake_fragment, 4, s,
  1068. s->msg_callback_arg);
  1069. if (SSL_is_init_finished(s) &&
  1070. !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS) &&
  1071. !s->s3->renegotiate) {
  1072. ssl3_renegotiate(s);
  1073. if (ssl3_renegotiate_check(s)) {
  1074. i = s->handshake_func(s);
  1075. if (i < 0)
  1076. return (i);
  1077. if (i == 0) {
  1078. SSLerr(SSL_F_SSL3_READ_BYTES,
  1079. SSL_R_SSL_HANDSHAKE_FAILURE);
  1080. return (-1);
  1081. }
  1082. if (!(s->mode & SSL_MODE_AUTO_RETRY)) {
  1083. if (s->s3->rbuf.left == 0) { /* no read-ahead left? */
  1084. BIO *bio;
  1085. /*
  1086. * In the case where we try to read application data,
  1087. * but we trigger an SSL handshake, we return -1 with
  1088. * the retry option set. Otherwise renegotiation may
  1089. * cause nasty problems in the blocking world
  1090. */
  1091. s->rwstate = SSL_READING;
  1092. bio = SSL_get_rbio(s);
  1093. BIO_clear_retry_flags(bio);
  1094. BIO_set_retry_read(bio);
  1095. return (-1);
  1096. }
  1097. }
  1098. }
  1099. }
  1100. /*
  1101. * we either finished a handshake or ignored the request, now try
  1102. * again to obtain the (application) data we were asked for
  1103. */
  1104. goto start;
  1105. }
  1106. /*
  1107. * If we are a server and get a client hello when renegotiation isn't
  1108. * allowed send back a no renegotiation alert and carry on. WARNING:
  1109. * experimental code, needs reviewing (steve)
  1110. */
  1111. if (s->server &&
  1112. SSL_is_init_finished(s) &&
  1113. !s->s3->send_connection_binding &&
  1114. (s->version > SSL3_VERSION) &&
  1115. (s->s3->handshake_fragment_len >= 4) &&
  1116. (s->s3->handshake_fragment[0] == SSL3_MT_CLIENT_HELLO) &&
  1117. (s->session != NULL) && (s->session->cipher != NULL) &&
  1118. !(s->ctx->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)) {
  1119. /*
  1120. * s->s3->handshake_fragment_len = 0;
  1121. */
  1122. rr->length = 0;
  1123. ssl3_send_alert(s, SSL3_AL_WARNING, SSL_AD_NO_RENEGOTIATION);
  1124. goto start;
  1125. }
  1126. if (s->s3->alert_fragment_len >= 2) {
  1127. int alert_level = s->s3->alert_fragment[0];
  1128. int alert_descr = s->s3->alert_fragment[1];
  1129. s->s3->alert_fragment_len = 0;
  1130. if (s->msg_callback)
  1131. s->msg_callback(0, s->version, SSL3_RT_ALERT,
  1132. s->s3->alert_fragment, 2, s, s->msg_callback_arg);
  1133. if (s->info_callback != NULL)
  1134. cb = s->info_callback;
  1135. else if (s->ctx->info_callback != NULL)
  1136. cb = s->ctx->info_callback;
  1137. if (cb != NULL) {
  1138. j = (alert_level << 8) | alert_descr;
  1139. cb(s, SSL_CB_READ_ALERT, j);
  1140. }
  1141. if (alert_level == SSL3_AL_WARNING) {
  1142. s->s3->warn_alert = alert_descr;
  1143. if (alert_descr == SSL_AD_CLOSE_NOTIFY) {
  1144. s->shutdown |= SSL_RECEIVED_SHUTDOWN;
  1145. return (0);
  1146. }
  1147. /*
  1148. * This is a warning but we receive it if we requested
  1149. * renegotiation and the peer denied it. Terminate with a fatal
  1150. * alert because if application tried to renegotiatie it
  1151. * presumably had a good reason and expects it to succeed. In
  1152. * future we might have a renegotiation where we don't care if
  1153. * the peer refused it where we carry on.
  1154. */
  1155. else if (alert_descr == SSL_AD_NO_RENEGOTIATION) {
  1156. al = SSL_AD_HANDSHAKE_FAILURE;
  1157. SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_NO_RENEGOTIATION);
  1158. goto f_err;
  1159. }
  1160. #ifdef SSL_AD_MISSING_SRP_USERNAME
  1161. else if (alert_descr == SSL_AD_MISSING_SRP_USERNAME)
  1162. return (0);
  1163. #endif
  1164. } else if (alert_level == SSL3_AL_FATAL) {
  1165. char tmp[16];
  1166. s->rwstate = SSL_NOTHING;
  1167. s->s3->fatal_alert = alert_descr;
  1168. SSLerr(SSL_F_SSL3_READ_BYTES, SSL_AD_REASON_OFFSET + alert_descr);
  1169. BIO_snprintf(tmp, sizeof tmp, "%d", alert_descr);
  1170. ERR_add_error_data(2, "SSL alert number ", tmp);
  1171. s->shutdown |= SSL_RECEIVED_SHUTDOWN;
  1172. SSL_CTX_remove_session(s->ctx, s->session);
  1173. return (0);
  1174. } else {
  1175. al = SSL_AD_ILLEGAL_PARAMETER;
  1176. SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_UNKNOWN_ALERT_TYPE);
  1177. goto f_err;
  1178. }
  1179. goto start;
  1180. }
  1181. if (s->shutdown & SSL_SENT_SHUTDOWN) { /* but we have not received a
  1182. * shutdown */
  1183. s->rwstate = SSL_NOTHING;
  1184. rr->length = 0;
  1185. return (0);
  1186. }
  1187. if (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC) {
  1188. /*
  1189. * 'Change Cipher Spec' is just a single byte, so we know exactly
  1190. * what the record payload has to look like
  1191. */
  1192. if ((rr->length != 1) || (rr->off != 0) ||
  1193. (rr->data[0] != SSL3_MT_CCS)) {
  1194. al = SSL_AD_ILLEGAL_PARAMETER;
  1195. SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_BAD_CHANGE_CIPHER_SPEC);
  1196. goto f_err;
  1197. }
  1198. /* Check we have a cipher to change to */
  1199. if (s->s3->tmp.new_cipher == NULL) {
  1200. al = SSL_AD_UNEXPECTED_MESSAGE;
  1201. SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_CCS_RECEIVED_EARLY);
  1202. goto f_err;
  1203. }
  1204. if (!(s->s3->flags & SSL3_FLAGS_CCS_OK)) {
  1205. al = SSL_AD_UNEXPECTED_MESSAGE;
  1206. SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_CCS_RECEIVED_EARLY);
  1207. goto f_err;
  1208. }
  1209. s->s3->flags &= ~SSL3_FLAGS_CCS_OK;
  1210. rr->length = 0;
  1211. if (s->msg_callback)
  1212. s->msg_callback(0, s->version, SSL3_RT_CHANGE_CIPHER_SPEC,
  1213. rr->data, 1, s, s->msg_callback_arg);
  1214. s->s3->change_cipher_spec = 1;
  1215. if (!ssl3_do_change_cipher_spec(s))
  1216. goto err;
  1217. else
  1218. goto start;
  1219. }
  1220. /*
  1221. * Unexpected handshake message (Client Hello, or protocol violation)
  1222. */
  1223. if ((s->s3->handshake_fragment_len >= 4) && !s->in_handshake) {
  1224. if (((s->state & SSL_ST_MASK) == SSL_ST_OK) &&
  1225. !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS)) {
  1226. #if 0 /* worked only because C operator preferences
  1227. * are not as expected (and because this is
  1228. * not really needed for clients except for
  1229. * detecting protocol violations): */
  1230. s->state = SSL_ST_BEFORE | (s->server)
  1231. ? SSL_ST_ACCEPT : SSL_ST_CONNECT;
  1232. #else
  1233. s->state = s->server ? SSL_ST_ACCEPT : SSL_ST_CONNECT;
  1234. #endif
  1235. s->renegotiate = 1;
  1236. s->new_session = 1;
  1237. }
  1238. i = s->handshake_func(s);
  1239. if (i < 0)
  1240. return (i);
  1241. if (i == 0) {
  1242. SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE);
  1243. return (-1);
  1244. }
  1245. if (!(s->mode & SSL_MODE_AUTO_RETRY)) {
  1246. if (s->s3->rbuf.left == 0) { /* no read-ahead left? */
  1247. BIO *bio;
  1248. /*
  1249. * In the case where we try to read application data, but we
  1250. * trigger an SSL handshake, we return -1 with the retry
  1251. * option set. Otherwise renegotiation may cause nasty
  1252. * problems in the blocking world
  1253. */
  1254. s->rwstate = SSL_READING;
  1255. bio = SSL_get_rbio(s);
  1256. BIO_clear_retry_flags(bio);
  1257. BIO_set_retry_read(bio);
  1258. return (-1);
  1259. }
  1260. }
  1261. goto start;
  1262. }
  1263. switch (rr->type) {
  1264. default:
  1265. #ifndef OPENSSL_NO_TLS
  1266. /*
  1267. * TLS up to v1.1 just ignores unknown message types: TLS v1.2 give
  1268. * an unexpected message alert.
  1269. */
  1270. if (s->version >= TLS1_VERSION && s->version <= TLS1_1_VERSION) {
  1271. rr->length = 0;
  1272. goto start;
  1273. }
  1274. #endif
  1275. al = SSL_AD_UNEXPECTED_MESSAGE;
  1276. SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_UNEXPECTED_RECORD);
  1277. goto f_err;
  1278. case SSL3_RT_CHANGE_CIPHER_SPEC:
  1279. case SSL3_RT_ALERT:
  1280. case SSL3_RT_HANDSHAKE:
  1281. /*
  1282. * we already handled all of these, with the possible exception of
  1283. * SSL3_RT_HANDSHAKE when s->in_handshake is set, but that should not
  1284. * happen when type != rr->type
  1285. */
  1286. al = SSL_AD_UNEXPECTED_MESSAGE;
  1287. SSLerr(SSL_F_SSL3_READ_BYTES, ERR_R_INTERNAL_ERROR);
  1288. goto f_err;
  1289. case SSL3_RT_APPLICATION_DATA:
  1290. /*
  1291. * At this point, we were expecting handshake data, but have
  1292. * application data. If the library was running inside ssl3_read()
  1293. * (i.e. in_read_app_data is set) and it makes sense to read
  1294. * application data at this point (session renegotiation not yet
  1295. * started), we will indulge it.
  1296. */
  1297. if (s->s3->in_read_app_data &&
  1298. (s->s3->total_renegotiations != 0) &&
  1299. (((s->state & SSL_ST_CONNECT) &&
  1300. (s->state >= SSL3_ST_CW_CLNT_HELLO_A) &&
  1301. (s->state <= SSL3_ST_CR_SRVR_HELLO_A)
  1302. ) || ((s->state & SSL_ST_ACCEPT) &&
  1303. (s->state <= SSL3_ST_SW_HELLO_REQ_A) &&
  1304. (s->state >= SSL3_ST_SR_CLNT_HELLO_A)
  1305. )
  1306. )) {
  1307. s->s3->in_read_app_data = 2;
  1308. return (-1);
  1309. } else {
  1310. al = SSL_AD_UNEXPECTED_MESSAGE;
  1311. SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_UNEXPECTED_RECORD);
  1312. goto f_err;
  1313. }
  1314. }
  1315. /* not reached */
  1316. f_err:
  1317. ssl3_send_alert(s, SSL3_AL_FATAL, al);
  1318. err:
  1319. return (-1);
  1320. }
  1321. int ssl3_do_change_cipher_spec(SSL *s)
  1322. {
  1323. int i;
  1324. const char *sender;
  1325. int slen;
  1326. if (s->state & SSL_ST_ACCEPT)
  1327. i = SSL3_CHANGE_CIPHER_SERVER_READ;
  1328. else
  1329. i = SSL3_CHANGE_CIPHER_CLIENT_READ;
  1330. if (s->s3->tmp.key_block == NULL) {
  1331. if (s->session == NULL || s->session->master_key_length == 0) {
  1332. /* might happen if dtls1_read_bytes() calls this */
  1333. SSLerr(SSL_F_SSL3_DO_CHANGE_CIPHER_SPEC,
  1334. SSL_R_CCS_RECEIVED_EARLY);
  1335. return (0);
  1336. }
  1337. s->session->cipher = s->s3->tmp.new_cipher;
  1338. if (!s->method->ssl3_enc->setup_key_block(s))
  1339. return (0);
  1340. }
  1341. if (!s->method->ssl3_enc->change_cipher_state(s, i))
  1342. return (0);
  1343. /*
  1344. * we have to record the message digest at this point so we can get it
  1345. * before we read the finished message
  1346. */
  1347. if (s->state & SSL_ST_CONNECT) {
  1348. sender = s->method->ssl3_enc->server_finished_label;
  1349. slen = s->method->ssl3_enc->server_finished_label_len;
  1350. } else {
  1351. sender = s->method->ssl3_enc->client_finished_label;
  1352. slen = s->method->ssl3_enc->client_finished_label_len;
  1353. }
  1354. i = s->method->ssl3_enc->final_finish_mac(s,
  1355. sender, slen,
  1356. s->s3->tmp.peer_finish_md);
  1357. if (i == 0) {
  1358. SSLerr(SSL_F_SSL3_DO_CHANGE_CIPHER_SPEC, ERR_R_INTERNAL_ERROR);
  1359. return 0;
  1360. }
  1361. s->s3->tmp.peer_finish_md_len = i;
  1362. return (1);
  1363. }
  1364. int ssl3_send_alert(SSL *s, int level, int desc)
  1365. {
  1366. /* Map tls/ssl alert value to correct one */
  1367. desc = s->method->ssl3_enc->alert_value(desc);
  1368. if (s->version == SSL3_VERSION && desc == SSL_AD_PROTOCOL_VERSION)
  1369. desc = SSL_AD_HANDSHAKE_FAILURE; /* SSL 3.0 does not have
  1370. * protocol_version alerts */
  1371. if (desc < 0)
  1372. return -1;
  1373. /* If a fatal one, remove from cache */
  1374. if ((level == 2) && (s->session != NULL))
  1375. SSL_CTX_remove_session(s->ctx, s->session);
  1376. s->s3->alert_dispatch = 1;
  1377. s->s3->send_alert[0] = level;
  1378. s->s3->send_alert[1] = desc;
  1379. if (s->s3->wbuf.left == 0) /* data still being written out? */
  1380. return s->method->ssl_dispatch_alert(s);
  1381. /*
  1382. * else data is still being written out, we will get written some time in
  1383. * the future
  1384. */
  1385. return -1;
  1386. }
  1387. int ssl3_dispatch_alert(SSL *s)
  1388. {
  1389. int i, j;
  1390. void (*cb) (const SSL *ssl, int type, int val) = NULL;
  1391. s->s3->alert_dispatch = 0;
  1392. i = do_ssl3_write(s, SSL3_RT_ALERT, &s->s3->send_alert[0], 2, 0);
  1393. if (i <= 0) {
  1394. s->s3->alert_dispatch = 1;
  1395. } else {
  1396. /*
  1397. * Alert sent to BIO. If it is important, flush it now. If the
  1398. * message does not get sent due to non-blocking IO, we will not
  1399. * worry too much.
  1400. */
  1401. if (s->s3->send_alert[0] == SSL3_AL_FATAL)
  1402. (void)BIO_flush(s->wbio);
  1403. if (s->msg_callback)
  1404. s->msg_callback(1, s->version, SSL3_RT_ALERT, s->s3->send_alert,
  1405. 2, s, s->msg_callback_arg);
  1406. if (s->info_callback != NULL)
  1407. cb = s->info_callback;
  1408. else if (s->ctx->info_callback != NULL)
  1409. cb = s->ctx->info_callback;
  1410. if (cb != NULL) {
  1411. j = (s->s3->send_alert[0] << 8) | s->s3->send_alert[1];
  1412. cb(s, SSL_CB_WRITE_ALERT, j);
  1413. }
  1414. }
  1415. return (i);
  1416. }