s3_pkt.c 42 KB

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