Move SSL3_RECORD oriented functions into ssl3_record.c
[openssl.git] / ssl / record / ssl3_record.c
1 /* ssl/record/ssl3_record.c */
2 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
3  * All rights reserved.
4  *
5  * This package is an SSL implementation written
6  * by Eric Young (eay@cryptsoft.com).
7  * The implementation was written so as to conform with Netscapes SSL.
8  *
9  * This library is free for commercial and non-commercial use as long as
10  * the following conditions are aheared to.  The following conditions
11  * apply to all code found in this distribution, be it the RC4, RSA,
12  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
13  * included with this distribution is covered by the same copyright terms
14  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
15  *
16  * Copyright remains Eric Young's, and as such any Copyright notices in
17  * the code are not to be removed.
18  * If this package is used in a product, Eric Young should be given attribution
19  * as the author of the parts of the library used.
20  * This can be in the form of a textual message at program startup or
21  * in documentation (online or textual) provided with the package.
22  *
23  * Redistribution and use in source and binary forms, with or without
24  * modification, are permitted provided that the following conditions
25  * are met:
26  * 1. Redistributions of source code must retain the copyright
27  *    notice, this list of conditions and the following disclaimer.
28  * 2. Redistributions in binary form must reproduce the above copyright
29  *    notice, this list of conditions and the following disclaimer in the
30  *    documentation and/or other materials provided with the distribution.
31  * 3. All advertising materials mentioning features or use of this software
32  *    must display the following acknowledgement:
33  *    "This product includes cryptographic software written by
34  *     Eric Young (eay@cryptsoft.com)"
35  *    The word 'cryptographic' can be left out if the rouines from the library
36  *    being used are not cryptographic related :-).
37  * 4. If you include any Windows specific code (or a derivative thereof) from
38  *    the apps directory (application code) you must include an acknowledgement:
39  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
40  *
41  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
42  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
43  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
44  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
45  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
46  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
47  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
49  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
50  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51  * SUCH DAMAGE.
52  *
53  * The licence and distribution terms for any publically available version or
54  * derivative of this code cannot be changed.  i.e. this code cannot simply be
55  * copied and put under another distribution licence
56  * [including the GNU Public Licence.]
57  */
58 /* ====================================================================
59  * Copyright (c) 1998-2015 The OpenSSL Project.  All rights reserved.
60  *
61  * Redistribution and use in source and binary forms, with or without
62  * modification, are permitted provided that the following conditions
63  * are met:
64  *
65  * 1. Redistributions of source code must retain the above copyright
66  *    notice, this list of conditions and the following disclaimer.
67  *
68  * 2. Redistributions in binary form must reproduce the above copyright
69  *    notice, this list of conditions and the following disclaimer in
70  *    the documentation and/or other materials provided with the
71  *    distribution.
72  *
73  * 3. All advertising materials mentioning features or use of this
74  *    software must display the following acknowledgment:
75  *    "This product includes software developed by the OpenSSL Project
76  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
77  *
78  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
79  *    endorse or promote products derived from this software without
80  *    prior written permission. For written permission, please contact
81  *    openssl-core@openssl.org.
82  *
83  * 5. Products derived from this software may not be called "OpenSSL"
84  *    nor may "OpenSSL" appear in their names without prior written
85  *    permission of the OpenSSL Project.
86  *
87  * 6. Redistributions of any form whatsoever must retain the following
88  *    acknowledgment:
89  *    "This product includes software developed by the OpenSSL Project
90  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
91  *
92  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
93  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
94  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
95  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
96  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
97  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
98  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
99  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
100  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
101  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
102  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
103  * OF THE POSSIBILITY OF SUCH DAMAGE.
104  * ====================================================================
105  *
106  * This product includes cryptographic software written by Eric Young
107  * (eay@cryptsoft.com).  This product includes software written by Tim
108  * Hudson (tjh@cryptsoft.com).
109  *
110  */
111
112 #include "../ssl_locl.h"
113
114 void SSL3_RECORD_clear(SSL3_RECORD *r)
115 {
116     memset(r->seq_num, 0, sizeof(r->seq_num));
117 }
118
119 void SSL3_RECORD_release(SSL3_RECORD *r)
120 {
121     if (r->comp != NULL)
122         OPENSSL_free(r->comp);
123     r->comp = NULL;
124 }
125
126 int SSL3_RECORD_setup(SSL3_RECORD *r, size_t len)
127 {
128     if (r->comp == NULL)
129         r->comp = (unsigned char *) OPENSSL_malloc(len);
130     if (r->comp == NULL)
131         return 0;
132     return 1;
133 }
134
135 void SSL3_RECORD_set_seq_num(SSL3_RECORD *r, const unsigned char *seq_num)
136 {
137     memcpy(r->seq_num, seq_num, 8);
138 }
139
140 /*
141  * MAX_EMPTY_RECORDS defines the number of consecutive, empty records that
142  * will be processed per call to ssl3_get_record. Without this limit an
143  * attacker could send empty records at a faster rate than we can process and
144  * cause ssl3_get_record to loop forever.
145  */
146 #define MAX_EMPTY_RECORDS 32
147
148 /*-
149  * Call this to get a new input record.
150  * It will return <= 0 if more data is needed, normally due to an error
151  * or non-blocking IO.
152  * When it finishes, one packet has been decoded and can be found in
153  * ssl->s3->rrec.type    - is the type of record
154  * ssl->s3->rrec.data,   - data
155  * ssl->s3->rrec.length, - number of bytes
156  */
157 /* used only by ssl3_read_bytes */
158 int ssl3_get_record(SSL *s)
159 {
160     int ssl_major, ssl_minor, al;
161     int enc_err, n, i, ret = -1;
162     SSL3_RECORD *rr;
163     SSL_SESSION *sess;
164     unsigned char *p;
165     unsigned char md[EVP_MAX_MD_SIZE];
166     short version;
167     unsigned mac_size;
168     size_t extra;
169     unsigned empty_record_count = 0;
170
171     rr = RECORD_LAYER_get_rrec(&s->rlayer);
172     sess = s->session;
173
174     if (s->options & SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER)
175         extra = SSL3_RT_MAX_EXTRA;
176     else
177         extra = 0;
178     if (extra && !s->s3->init_extra) {
179         /*
180          * An application error: SLS_OP_MICROSOFT_BIG_SSLV3_BUFFER set after
181          * ssl3_setup_buffers() was done
182          */
183         SSLerr(SSL_F_SSL3_GET_RECORD, ERR_R_INTERNAL_ERROR);
184         return -1;
185     }
186
187  again:
188     /* check if we have the header */
189     if ((s->rstate != SSL_ST_READ_BODY) ||
190         (s->packet_length < SSL3_RT_HEADER_LENGTH)) {
191         n = ssl3_read_n(s, SSL3_RT_HEADER_LENGTH,
192             SSL3_BUFFER_get_len(RECORD_LAYER_get_rbuf(&s->rlayer)), 0);
193         if (n <= 0)
194             return (n);         /* error or non-blocking */
195         s->rstate = SSL_ST_READ_BODY;
196
197         p = s->packet;
198         if (s->msg_callback)
199             s->msg_callback(0, 0, SSL3_RT_HEADER, p, 5, s,
200                             s->msg_callback_arg);
201
202         /* Pull apart the header into the SSL3_RECORD */
203         rr->type = *(p++);
204         ssl_major = *(p++);
205         ssl_minor = *(p++);
206         version = (ssl_major << 8) | ssl_minor;
207         n2s(p, rr->length);
208
209         /* Lets check version */
210         if (!s->first_packet) {
211             if (version != s->version) {
212                 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_WRONG_VERSION_NUMBER);
213                 if ((s->version & 0xFF00) == (version & 0xFF00)
214                     && !s->enc_write_ctx && !s->write_hash)
215                     /*
216                      * Send back error using their minor version number :-)
217                      */
218                     s->version = (unsigned short)version;
219                 al = SSL_AD_PROTOCOL_VERSION;
220                 goto f_err;
221             }
222         }
223
224         if ((version >> 8) != SSL3_VERSION_MAJOR) {
225             SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_WRONG_VERSION_NUMBER);
226             goto err;
227         }
228
229         if (rr->length >
230                 SSL3_BUFFER_get_len(RECORD_LAYER_get_rbuf(&s->rlayer))
231                 - SSL3_RT_HEADER_LENGTH) {
232             al = SSL_AD_RECORD_OVERFLOW;
233             SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_PACKET_LENGTH_TOO_LONG);
234             goto f_err;
235         }
236
237         /* now s->rstate == SSL_ST_READ_BODY */
238     }
239
240     /* s->rstate == SSL_ST_READ_BODY, get and decode the data */
241
242     if (rr->length > s->packet_length - SSL3_RT_HEADER_LENGTH) {
243         /* now s->packet_length == SSL3_RT_HEADER_LENGTH */
244         i = rr->length;
245         n = ssl3_read_n(s, i, i, 1);
246         if (n <= 0)
247             return (n);         /* error or non-blocking io */
248         /*
249          * now n == rr->length, and s->packet_length == SSL3_RT_HEADER_LENGTH
250          * + rr->length
251          */
252     }
253
254     s->rstate = SSL_ST_READ_HEADER; /* set state for later operations */
255
256     /*
257      * At this point, s->packet_length == SSL3_RT_HEADER_LNGTH + rr->length,
258      * and we have that many bytes in s->packet
259      */
260     rr->input = &(s->packet[SSL3_RT_HEADER_LENGTH]);
261
262     /*
263      * ok, we can now read from 's->packet' data into 'rr' rr->input points
264      * at rr->length bytes, which need to be copied into rr->data by either
265      * the decryption or by the decompression When the data is 'copied' into
266      * the rr->data buffer, rr->input will be pointed at the new buffer
267      */
268
269     /*
270      * We now have - encrypted [ MAC [ compressed [ plain ] ] ] rr->length
271      * bytes of encrypted compressed stuff.
272      */
273
274     /* check is not needed I believe */
275     if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH + extra) {
276         al = SSL_AD_RECORD_OVERFLOW;
277         SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
278         goto f_err;
279     }
280
281     /* decrypt in place in 'rr->input' */
282     rr->data = rr->input;
283     rr->orig_len = rr->length;
284     /*
285      * If in encrypt-then-mac mode calculate mac from encrypted record. All
286      * the details below are public so no timing details can leak.
287      */
288     if (SSL_USE_ETM(s) && s->read_hash) {
289         unsigned char *mac;
290         mac_size = EVP_MD_CTX_size(s->read_hash);
291         OPENSSL_assert(mac_size <= EVP_MAX_MD_SIZE);
292         if (rr->length < mac_size) {
293             al = SSL_AD_DECODE_ERROR;
294             SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_LENGTH_TOO_SHORT);
295             goto f_err;
296         }
297         rr->length -= mac_size;
298         mac = rr->data + rr->length;
299         i = s->method->ssl3_enc->mac(s, md, 0 /* not send */ );
300         if (i < 0 || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0) {
301             al = SSL_AD_BAD_RECORD_MAC;
302             SSLerr(SSL_F_SSL3_GET_RECORD,
303                    SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
304             goto f_err;
305         }
306     }
307
308     enc_err = s->method->ssl3_enc->enc(s, 0);
309     /*-
310      * enc_err is:
311      *    0: (in non-constant time) if the record is publically invalid.
312      *    1: if the padding is valid
313      *    -1: if the padding is invalid
314      */
315     if (enc_err == 0) {
316         al = SSL_AD_DECRYPTION_FAILED;
317         SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_BLOCK_CIPHER_PAD_IS_WRONG);
318         goto f_err;
319     }
320 #ifdef TLS_DEBUG
321     printf("dec %d\n", rr->length);
322     {
323         unsigned int z;
324         for (z = 0; z < rr->length; z++)
325             printf("%02X%c", rr->data[z], ((z + 1) % 16) ? ' ' : '\n');
326     }
327     printf("\n");
328 #endif
329
330     /* r->length is now the compressed data plus mac */
331     if ((sess != NULL) &&
332         (s->enc_read_ctx != NULL) &&
333         (EVP_MD_CTX_md(s->read_hash) != NULL) && !SSL_USE_ETM(s)) {
334         /* s->read_hash != NULL => mac_size != -1 */
335         unsigned char *mac = NULL;
336         unsigned char mac_tmp[EVP_MAX_MD_SIZE];
337         mac_size = EVP_MD_CTX_size(s->read_hash);
338         OPENSSL_assert(mac_size <= EVP_MAX_MD_SIZE);
339
340         /*
341          * orig_len is the length of the record before any padding was
342          * removed. This is public information, as is the MAC in use,
343          * therefore we can safely process the record in a different amount
344          * of time if it's too short to possibly contain a MAC.
345          */
346         if (rr->orig_len < mac_size ||
347             /* CBC records must have a padding length byte too. */
348             (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
349              rr->orig_len < mac_size + 1)) {
350             al = SSL_AD_DECODE_ERROR;
351             SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_LENGTH_TOO_SHORT);
352             goto f_err;
353         }
354
355         if (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE) {
356             /*
357              * We update the length so that the TLS header bytes can be
358              * constructed correctly but we need to extract the MAC in
359              * constant time from within the record, without leaking the
360              * contents of the padding bytes.
361              */
362             mac = mac_tmp;
363             ssl3_cbc_copy_mac(mac_tmp, rr, mac_size);
364             rr->length -= mac_size;
365         } else {
366             /*
367              * In this case there's no padding, so |rec->orig_len| equals
368              * |rec->length| and we checked that there's enough bytes for
369              * |mac_size| above.
370              */
371             rr->length -= mac_size;
372             mac = &rr->data[rr->length];
373         }
374
375         i = s->method->ssl3_enc->mac(s, md, 0 /* not send */ );
376         if (i < 0 || mac == NULL
377             || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0)
378             enc_err = -1;
379         if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH + extra + mac_size)
380             enc_err = -1;
381     }
382
383     if (enc_err < 0) {
384         /*
385          * A separate 'decryption_failed' alert was introduced with TLS 1.0,
386          * SSL 3.0 only has 'bad_record_mac'.  But unless a decryption
387          * failure is directly visible from the ciphertext anyway, we should
388          * not reveal which kind of error occurred -- this might become
389          * visible to an attacker (e.g. via a logfile)
390          */
391         al = SSL_AD_BAD_RECORD_MAC;
392         SSLerr(SSL_F_SSL3_GET_RECORD,
393                SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
394         goto f_err;
395     }
396
397     /* r->length is now just compressed */
398     if (s->expand != NULL) {
399         if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH + extra) {
400             al = SSL_AD_RECORD_OVERFLOW;
401             SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_COMPRESSED_LENGTH_TOO_LONG);
402             goto f_err;
403         }
404         if (!ssl3_do_uncompress(s)) {
405             al = SSL_AD_DECOMPRESSION_FAILURE;
406             SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_BAD_DECOMPRESSION);
407             goto f_err;
408         }
409     }
410
411     if (rr->length > SSL3_RT_MAX_PLAIN_LENGTH + extra) {
412         al = SSL_AD_RECORD_OVERFLOW;
413         SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_DATA_LENGTH_TOO_LONG);
414         goto f_err;
415     }
416
417     rr->off = 0;
418     /*-
419      * So at this point the following is true
420      * ssl->s3->rrec.type   is the type of record
421      * ssl->s3->rrec.length == number of bytes in record
422      * ssl->s3->rrec.off    == offset to first valid byte
423      * ssl->s3->rrec.data   == where to take bytes from, increment
424      *                         after use :-).
425      */
426
427     /* we have pulled in a full packet so zero things */
428     s->packet_length = 0;
429
430     /* just read a 0 length packet */
431     if (rr->length == 0) {
432         empty_record_count++;
433         if (empty_record_count > MAX_EMPTY_RECORDS) {
434             al = SSL_AD_UNEXPECTED_MESSAGE;
435             SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_RECORD_TOO_SMALL);
436             goto f_err;
437         }
438         goto again;
439     }
440
441     return (1);
442
443  f_err:
444     ssl3_send_alert(s, SSL3_AL_FATAL, al);
445  err:
446     return (ret);
447 }
448
449 int ssl3_do_uncompress(SSL *ssl)
450 {
451 #ifndef OPENSSL_NO_COMP
452     int i;
453     SSL3_RECORD *rr;
454
455     rr = RECORD_LAYER_get_rrec(&ssl->rlayer);
456     i = COMP_expand_block(ssl->expand, rr->comp,
457                           SSL3_RT_MAX_PLAIN_LENGTH, rr->data,
458                           (int)rr->length);
459     if (i < 0)
460         return (0);
461     else
462         rr->length = i;
463     rr->data = rr->comp;
464 #endif
465     return (1);
466 }
467
468 int ssl3_do_compress(SSL *ssl)
469 {
470 #ifndef OPENSSL_NO_COMP
471     int i;
472     SSL3_RECORD *wr;
473
474     wr = RECORD_LAYER_get_wrec(&ssl->rlayer);
475     i = COMP_compress_block(ssl->compress, wr->data,
476                             SSL3_RT_MAX_COMPRESSED_LENGTH,
477                             wr->input, (int)wr->length);
478     if (i < 0)
479         return (0);
480     else
481         wr->length = i;
482
483     wr->input = wr->data;
484 #endif
485     return (1);
486 }
487
488 int dtls1_process_record(SSL *s)
489 {
490     int i, al;
491     int enc_err;
492     SSL_SESSION *sess;
493     SSL3_RECORD *rr;
494     unsigned int mac_size;
495     unsigned char md[EVP_MAX_MD_SIZE];
496
497     rr = RECORD_LAYER_get_rrec(&s->rlayer);
498     sess = s->session;
499
500     /*
501      * At this point, s->packet_length == SSL3_RT_HEADER_LNGTH + rr->length,
502      * and we have that many bytes in s->packet
503      */
504     rr->input = &(s->packet[DTLS1_RT_HEADER_LENGTH]);
505
506     /*
507      * ok, we can now read from 's->packet' data into 'rr' rr->input points
508      * at rr->length bytes, which need to be copied into rr->data by either
509      * the decryption or by the decompression When the data is 'copied' into
510      * the rr->data buffer, rr->input will be pointed at the new buffer
511      */
512
513     /*
514      * We now have - encrypted [ MAC [ compressed [ plain ] ] ] rr->length
515      * bytes of encrypted compressed stuff.
516      */
517
518     /* check is not needed I believe */
519     if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
520         al = SSL_AD_RECORD_OVERFLOW;
521         SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
522         goto f_err;
523     }
524
525     /* decrypt in place in 'rr->input' */
526     rr->data = rr->input;
527     rr->orig_len = rr->length;
528
529     enc_err = s->method->ssl3_enc->enc(s, 0);
530     /*-
531      * enc_err is:
532      *    0: (in non-constant time) if the record is publically invalid.
533      *    1: if the padding is valid
534      *   -1: if the padding is invalid
535      */
536     if (enc_err == 0) {
537         /* For DTLS we simply ignore bad packets. */
538         rr->length = 0;
539         s->packet_length = 0;
540         goto err;
541     }
542 #ifdef TLS_DEBUG
543     printf("dec %d\n", rr->length);
544     {
545         unsigned int z;
546         for (z = 0; z < rr->length; z++)
547             printf("%02X%c", rr->data[z], ((z + 1) % 16) ? ' ' : '\n');
548     }
549     printf("\n");
550 #endif
551
552     /* r->length is now the compressed data plus mac */
553     if ((sess != NULL) &&
554         (s->enc_read_ctx != NULL) && (EVP_MD_CTX_md(s->read_hash) != NULL)) {
555         /* s->read_hash != NULL => mac_size != -1 */
556         unsigned char *mac = NULL;
557         unsigned char mac_tmp[EVP_MAX_MD_SIZE];
558         mac_size = EVP_MD_CTX_size(s->read_hash);
559         OPENSSL_assert(mac_size <= EVP_MAX_MD_SIZE);
560
561         /*
562          * orig_len is the length of the record before any padding was
563          * removed. This is public information, as is the MAC in use,
564          * therefore we can safely process the record in a different amount
565          * of time if it's too short to possibly contain a MAC.
566          */
567         if (rr->orig_len < mac_size ||
568             /* CBC records must have a padding length byte too. */
569             (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
570              rr->orig_len < mac_size + 1)) {
571             al = SSL_AD_DECODE_ERROR;
572             SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_LENGTH_TOO_SHORT);
573             goto f_err;
574         }
575
576         if (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE) {
577             /*
578              * We update the length so that the TLS header bytes can be
579              * constructed correctly but we need to extract the MAC in
580              * constant time from within the record, without leaking the
581              * contents of the padding bytes.
582              */
583             mac = mac_tmp;
584             ssl3_cbc_copy_mac(mac_tmp, rr, mac_size);
585             rr->length -= mac_size;
586         } else {
587             /*
588              * In this case there's no padding, so |rec->orig_len| equals
589              * |rec->length| and we checked that there's enough bytes for
590              * |mac_size| above.
591              */
592             rr->length -= mac_size;
593             mac = &rr->data[rr->length];
594         }
595
596         i = s->method->ssl3_enc->mac(s, md, 0 /* not send */ );
597         if (i < 0 || mac == NULL
598             || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0)
599             enc_err = -1;
600         if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH + mac_size)
601             enc_err = -1;
602     }
603
604     if (enc_err < 0) {
605         /* decryption failed, silently discard message */
606         rr->length = 0;
607         s->packet_length = 0;
608         goto err;
609     }
610
611     /* r->length is now just compressed */
612     if (s->expand != NULL) {
613         if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH) {
614             al = SSL_AD_RECORD_OVERFLOW;
615             SSLerr(SSL_F_DTLS1_PROCESS_RECORD,
616                    SSL_R_COMPRESSED_LENGTH_TOO_LONG);
617             goto f_err;
618         }
619         if (!ssl3_do_uncompress(s)) {
620             al = SSL_AD_DECOMPRESSION_FAILURE;
621             SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_BAD_DECOMPRESSION);
622             goto f_err;
623         }
624     }
625
626     if (rr->length > SSL3_RT_MAX_PLAIN_LENGTH) {
627         al = SSL_AD_RECORD_OVERFLOW;
628         SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_DATA_LENGTH_TOO_LONG);
629         goto f_err;
630     }
631
632     rr->off = 0;
633     /*-
634      * So at this point the following is true
635      * ssl->s3->rrec.type   is the type of record
636      * ssl->s3->rrec.length == number of bytes in record
637      * ssl->s3->rrec.off    == offset to first valid byte
638      * ssl->s3->rrec.data   == where to take bytes from, increment
639      *                         after use :-).
640      */
641
642     /* we have pulled in a full packet so zero things */
643     s->packet_length = 0;
644     return (1);
645
646  f_err:
647     ssl3_send_alert(s, SSL3_AL_FATAL, al);
648  err:
649     return (0);
650 }
651
652
653 /*
654  * retrieve a buffered record that belongs to the current epoch, ie,
655  * processed
656  */
657 #define dtls1_get_processed_record(s) \
658                    dtls1_retrieve_buffered_record((s), \
659                    &((s)->d1->processed_rcds))
660
661 /*-
662  * Call this to get a new input record.
663  * It will return <= 0 if more data is needed, normally due to an error
664  * or non-blocking IO.
665  * When it finishes, one packet has been decoded and can be found in
666  * ssl->s3->rrec.type    - is the type of record
667  * ssl->s3->rrec.data,   - data
668  * ssl->s3->rrec.length, - number of bytes
669  */
670 /* used only by dtls1_read_bytes */
671 int dtls1_get_record(SSL *s)
672 {
673     int ssl_major, ssl_minor;
674     int i, n;
675     SSL3_RECORD *rr;
676     unsigned char *p = NULL;
677     unsigned short version;
678     DTLS1_BITMAP *bitmap;
679     unsigned int is_next_epoch;
680
681     rr = RECORD_LAYER_get_rrec(&s->rlayer);
682
683     /*
684      * The epoch may have changed.  If so, process all the pending records.
685      * This is a non-blocking operation.
686      */
687     if (dtls1_process_buffered_records(s) < 0)
688         return -1;
689
690     /* if we're renegotiating, then there may be buffered records */
691     if (dtls1_get_processed_record(s))
692         return 1;
693
694     /* get something from the wire */
695  again:
696     /* check if we have the header */
697     if ((s->rstate != SSL_ST_READ_BODY) ||
698         (s->packet_length < DTLS1_RT_HEADER_LENGTH)) {
699         n = ssl3_read_n(s, DTLS1_RT_HEADER_LENGTH,
700             SSL3_BUFFER_get_len(RECORD_LAYER_get_rbuf(&s->rlayer)), 0);
701         /* read timeout is handled by dtls1_read_bytes */
702         if (n <= 0)
703             return (n);         /* error or non-blocking */
704
705         /* this packet contained a partial record, dump it */
706         if (s->packet_length != DTLS1_RT_HEADER_LENGTH) {
707             s->packet_length = 0;
708             goto again;
709         }
710
711         s->rstate = SSL_ST_READ_BODY;
712
713         p = s->packet;
714
715         if (s->msg_callback)
716             s->msg_callback(0, 0, SSL3_RT_HEADER, p, DTLS1_RT_HEADER_LENGTH,
717                             s, s->msg_callback_arg);
718
719         /* Pull apart the header into the DTLS1_RECORD */
720         rr->type = *(p++);
721         ssl_major = *(p++);
722         ssl_minor = *(p++);
723         version = (ssl_major << 8) | ssl_minor;
724
725         /* sequence number is 64 bits, with top 2 bytes = epoch */
726         n2s(p, rr->epoch);
727
728         memcpy(&(s->s3->read_sequence[2]), p, 6);
729         p += 6;
730
731         n2s(p, rr->length);
732
733         /* Lets check version */
734         if (!s->first_packet) {
735             if (version != s->version) {
736                 /* unexpected version, silently discard */
737                 rr->length = 0;
738                 s->packet_length = 0;
739                 goto again;
740             }
741         }
742
743         if ((version & 0xff00) != (s->version & 0xff00)) {
744             /* wrong version, silently discard record */
745             rr->length = 0;
746             s->packet_length = 0;
747             goto again;
748         }
749
750         if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
751             /* record too long, silently discard it */
752             rr->length = 0;
753             s->packet_length = 0;
754             goto again;
755         }
756
757         /* now s->rstate == SSL_ST_READ_BODY */
758     }
759
760     /* s->rstate == SSL_ST_READ_BODY, get and decode the data */
761
762     if (rr->length > s->packet_length - DTLS1_RT_HEADER_LENGTH) {
763         /* now s->packet_length == DTLS1_RT_HEADER_LENGTH */
764         i = rr->length;
765         n = ssl3_read_n(s, i, i, 1);
766         /* this packet contained a partial record, dump it */
767         if (n != i) {
768             rr->length = 0;
769             s->packet_length = 0;
770             goto again;
771         }
772
773         /*
774          * now n == rr->length, and s->packet_length ==
775          * DTLS1_RT_HEADER_LENGTH + rr->length
776          */
777     }
778     s->rstate = SSL_ST_READ_HEADER; /* set state for later operations */
779
780     /* match epochs.  NULL means the packet is dropped on the floor */
781     bitmap = dtls1_get_bitmap(s, rr, &is_next_epoch);
782     if (bitmap == NULL) {
783         rr->length = 0;
784         s->packet_length = 0;   /* dump this record */
785         goto again;             /* get another record */
786     }
787 #ifndef OPENSSL_NO_SCTP
788     /* Only do replay check if no SCTP bio */
789     if (!BIO_dgram_is_sctp(SSL_get_rbio(s))) {
790 #endif
791         /*
792          * Check whether this is a repeat, or aged record. Don't check if
793          * we're listening and this message is a ClientHello. They can look
794          * as if they're replayed, since they arrive from different
795          * connections and would be dropped unnecessarily.
796          */
797         if (!(s->d1->listen && rr->type == SSL3_RT_HANDSHAKE &&
798               s->packet_length > DTLS1_RT_HEADER_LENGTH &&
799               s->packet[DTLS1_RT_HEADER_LENGTH] == SSL3_MT_CLIENT_HELLO) &&
800             !dtls1_record_replay_check(s, bitmap)) {
801             rr->length = 0;
802             s->packet_length = 0; /* dump this record */
803             goto again;         /* get another record */
804         }
805 #ifndef OPENSSL_NO_SCTP
806     }
807 #endif
808
809     /* just read a 0 length packet */
810     if (rr->length == 0)
811         goto again;
812
813     /*
814      * If this record is from the next epoch (either HM or ALERT), and a
815      * handshake is currently in progress, buffer it since it cannot be
816      * processed at this time. However, do not buffer anything while
817      * listening.
818      */
819     if (is_next_epoch) {
820         if ((SSL_in_init(s) || s->in_handshake) && !s->d1->listen) {
821             if (dtls1_buffer_record
822                 (s, &(s->d1->unprocessed_rcds), rr->seq_num) < 0)
823                 return -1;
824             /* Mark receipt of record. */
825             dtls1_record_bitmap_update(s, bitmap);
826         }
827         rr->length = 0;
828         s->packet_length = 0;
829         goto again;
830     }
831
832     if (!dtls1_process_record(s)) {
833         rr->length = 0;
834         s->packet_length = 0;   /* dump this record */
835         goto again;             /* get another record */
836     }
837     dtls1_record_bitmap_update(s, bitmap); /* Mark receipt of record. */
838
839     return (1);
840
841 }
842