s3_pkt.c 42 KB

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