Make sure we reset the read sequence when skipping records
[openssl.git] / ssl / record / ssl3_record.c
1 /*
2  * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the OpenSSL license (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9
10 #include <assert.h>
11 #include "../ssl_locl.h"
12 #include "internal/constant_time_locl.h"
13 #include <openssl/rand.h>
14 #include "record_locl.h"
15
16 static const unsigned char ssl3_pad_1[48] = {
17     0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
18     0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
19     0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
20     0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
21     0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
22     0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36
23 };
24
25 static const unsigned char ssl3_pad_2[48] = {
26     0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
27     0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
28     0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
29     0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
30     0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
31     0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c
32 };
33
34 /*
35  * Clear the contents of an SSL3_RECORD but retain any memory allocated
36  */
37 void SSL3_RECORD_clear(SSL3_RECORD *r, size_t num_recs)
38 {
39     unsigned char *comp;
40     size_t i;
41
42     for (i = 0; i < num_recs; i++) {
43         comp = r[i].comp;
44
45         memset(&r[i], 0, sizeof(*r));
46         r[i].comp = comp;
47     }
48 }
49
50 void SSL3_RECORD_release(SSL3_RECORD *r, size_t num_recs)
51 {
52     size_t i;
53
54     for (i = 0; i < num_recs; i++) {
55         OPENSSL_free(r[i].comp);
56         r[i].comp = NULL;
57     }
58 }
59
60 void SSL3_RECORD_set_seq_num(SSL3_RECORD *r, const unsigned char *seq_num)
61 {
62     memcpy(r->seq_num, seq_num, SEQ_NUM_SIZE);
63 }
64
65 /*
66  * Peeks ahead into "read_ahead" data to see if we have a whole record waiting
67  * for us in the buffer.
68  */
69 static int ssl3_record_app_data_waiting(SSL *s)
70 {
71     SSL3_BUFFER *rbuf;
72     size_t left, len;
73     unsigned char *p;
74
75     rbuf = RECORD_LAYER_get_rbuf(&s->rlayer);
76
77     p = SSL3_BUFFER_get_buf(rbuf);
78     if (p == NULL)
79         return 0;
80
81     left = SSL3_BUFFER_get_left(rbuf);
82
83     if (left < SSL3_RT_HEADER_LENGTH)
84         return 0;
85
86     p += SSL3_BUFFER_get_offset(rbuf);
87
88     /*
89      * We only check the type and record length, we will sanity check version
90      * etc later
91      */
92     if (*p != SSL3_RT_APPLICATION_DATA)
93         return 0;
94
95     p += 3;
96     n2s(p, len);
97
98     if (left < SSL3_RT_HEADER_LENGTH + len)
99         return 0;
100
101     return 1;
102 }
103
104 /*
105  * MAX_EMPTY_RECORDS defines the number of consecutive, empty records that
106  * will be processed per call to ssl3_get_record. Without this limit an
107  * attacker could send empty records at a faster rate than we can process and
108  * cause ssl3_get_record to loop forever.
109  */
110 #define MAX_EMPTY_RECORDS 32
111
112 #define SSL2_RT_HEADER_LENGTH   2
113 /*-
114  * Call this to get new input records.
115  * It will return <= 0 if more data is needed, normally due to an error
116  * or non-blocking IO.
117  * When it finishes, |numrpipes| records have been decoded. For each record 'i':
118  * rr[i].type    - is the type of record
119  * rr[i].data,   - data
120  * rr[i].length, - number of bytes
121  * Multiple records will only be returned if the record types are all
122  * SSL3_RT_APPLICATION_DATA. The number of records returned will always be <=
123  * |max_pipelines|
124  */
125 /* used only by ssl3_read_bytes */
126 int ssl3_get_record(SSL *s)
127 {
128     int al;
129     int enc_err, rret, ret = -1;
130     int i;
131     size_t more, n;
132     SSL3_RECORD *rr, *thisrr;
133     SSL3_BUFFER *rbuf;
134     SSL_SESSION *sess;
135     unsigned char *p;
136     unsigned char md[EVP_MAX_MD_SIZE];
137     unsigned int version;
138     size_t mac_size;
139     int imac_size;
140     size_t num_recs = 0, max_recs, j;
141     PACKET pkt, sslv2pkt;
142
143     rr = RECORD_LAYER_get_rrec(&s->rlayer);
144     rbuf = RECORD_LAYER_get_rbuf(&s->rlayer);
145     max_recs = s->max_pipelines;
146     if (max_recs == 0)
147         max_recs = 1;
148     sess = s->session;
149
150     do {
151         thisrr = &rr[num_recs];
152
153         /* check if we have the header */
154         if ((RECORD_LAYER_get_rstate(&s->rlayer) != SSL_ST_READ_BODY) ||
155             (RECORD_LAYER_get_packet_length(&s->rlayer)
156              < SSL3_RT_HEADER_LENGTH)) {
157             size_t sslv2len;
158             unsigned int type;
159
160             rret = ssl3_read_n(s, SSL3_RT_HEADER_LENGTH,
161                                SSL3_BUFFER_get_len(rbuf), 0,
162                                num_recs == 0 ? 1 : 0, &n);
163             if (rret <= 0)
164                 return rret;     /* error or non-blocking */
165             RECORD_LAYER_set_rstate(&s->rlayer, SSL_ST_READ_BODY);
166
167             p = RECORD_LAYER_get_packet(&s->rlayer);
168             if (!PACKET_buf_init(&pkt, RECORD_LAYER_get_packet(&s->rlayer),
169                                  RECORD_LAYER_get_packet_length(&s->rlayer))) {
170                 al = SSL_AD_INTERNAL_ERROR;
171                 SSLerr(SSL_F_SSL3_GET_RECORD, ERR_R_INTERNAL_ERROR);
172                 goto f_err;
173             }
174             sslv2pkt = pkt;
175             if (!PACKET_get_net_2_len(&sslv2pkt, &sslv2len)
176                     || !PACKET_get_1(&sslv2pkt, &type)) {
177                 al = SSL_AD_INTERNAL_ERROR;
178                 SSLerr(SSL_F_SSL3_GET_RECORD, ERR_R_INTERNAL_ERROR);
179                 goto f_err;
180             }
181             /*
182              * The first record received by the server may be a V2ClientHello.
183              */
184             if (s->server && RECORD_LAYER_is_first_record(&s->rlayer)
185                     && (sslv2len & 0x8000) != 0
186                     && (type == SSL2_MT_CLIENT_HELLO)) {
187                 /*
188                  *  SSLv2 style record
189                  *
190                  * |num_recs| here will actually always be 0 because
191                  * |num_recs > 0| only ever occurs when we are processing
192                  * multiple app data records - which we know isn't the case here
193                  * because it is an SSLv2ClientHello. We keep it using
194                  * |num_recs| for the sake of consistency
195                  */
196                 thisrr->type = SSL3_RT_HANDSHAKE;
197                 thisrr->rec_version = SSL2_VERSION;
198
199                 thisrr->length = sslv2len & 0x7fff;
200
201                 if (thisrr->length > SSL3_BUFFER_get_len(rbuf)
202                     - SSL2_RT_HEADER_LENGTH) {
203                     al = SSL_AD_RECORD_OVERFLOW;
204                     SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_PACKET_LENGTH_TOO_LONG);
205                     goto f_err;
206                 }
207
208                 if (thisrr->length < MIN_SSL2_RECORD_LEN) {
209                     al = SSL_AD_HANDSHAKE_FAILURE;
210                     SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_LENGTH_TOO_SHORT);
211                     goto f_err;
212                 }
213             } else {
214                 /* SSLv3+ style record */
215                 /*
216                  * TODO(TLS1.3): This callback only provides the "outer" record
217                  * type to the callback. Somehow we need to pass the "inner"
218                  * record type
219                  */
220                 if (s->msg_callback)
221                     s->msg_callback(0, 0, SSL3_RT_HEADER, p, 5, s,
222                                     s->msg_callback_arg);
223
224                 /* Pull apart the header into the SSL3_RECORD */
225                 if (!PACKET_get_1(&pkt, &type)
226                         || !PACKET_get_net_2(&pkt, &version)
227                         || !PACKET_get_net_2_len(&pkt, &thisrr->length)) {
228                     al = SSL_AD_INTERNAL_ERROR;
229                     SSLerr(SSL_F_SSL3_GET_RECORD, ERR_R_INTERNAL_ERROR);
230                     goto f_err;
231                 }
232                 thisrr->type = type;
233                 thisrr->rec_version = version;
234
235                 /* Lets check version. In TLSv1.3 we ignore this field */
236                 if (!s->first_packet && !SSL_IS_TLS13(s)
237                         && version != (unsigned int)s->version) {
238                     SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_WRONG_VERSION_NUMBER);
239                     if ((s->version & 0xFF00) == (version & 0xFF00)
240                         && !s->enc_write_ctx && !s->write_hash) {
241                         if (thisrr->type == SSL3_RT_ALERT) {
242                             /*
243                              * The record is using an incorrect version number,
244                              * but what we've got appears to be an alert. We
245                              * haven't read the body yet to check whether its a
246                              * fatal or not - but chances are it is. We probably
247                              * shouldn't send a fatal alert back. We'll just
248                              * end.
249                              */
250                             goto err;
251                         }
252                         /*
253                          * Send back error using their minor version number :-)
254                          */
255                         s->version = (unsigned short)version;
256                     }
257                     al = SSL_AD_PROTOCOL_VERSION;
258                     goto f_err;
259                 }
260
261                 if ((version >> 8) != SSL3_VERSION_MAJOR) {
262                     if (RECORD_LAYER_is_first_record(&s->rlayer)) {
263                         /* Go back to start of packet, look at the five bytes
264                          * that we have. */
265                         p = RECORD_LAYER_get_packet(&s->rlayer);
266                         if (strncmp((char *)p, "GET ", 4) == 0 ||
267                             strncmp((char *)p, "POST ", 5) == 0 ||
268                             strncmp((char *)p, "HEAD ", 5) == 0 ||
269                             strncmp((char *)p, "PUT ", 4) == 0) {
270                             SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_HTTP_REQUEST);
271                             goto err;
272                         } else if (strncmp((char *)p, "CONNE", 5) == 0) {
273                             SSLerr(SSL_F_SSL3_GET_RECORD,
274                                    SSL_R_HTTPS_PROXY_REQUEST);
275                             goto err;
276                         }
277
278                         /* Doesn't look like TLS - don't send an alert */
279                         SSLerr(SSL_F_SSL3_GET_RECORD,
280                                SSL_R_WRONG_VERSION_NUMBER);
281                         goto err;
282                     } else {
283                         SSLerr(SSL_F_SSL3_GET_RECORD,
284                                SSL_R_WRONG_VERSION_NUMBER);
285                         al = SSL_AD_PROTOCOL_VERSION;
286                         goto f_err;
287                     }
288                 }
289
290                 if (SSL_IS_TLS13(s) && s->enc_read_ctx != NULL
291                         && thisrr->type != SSL3_RT_APPLICATION_DATA) {
292                     SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_BAD_RECORD_TYPE);
293                     al = SSL_AD_UNEXPECTED_MESSAGE;
294                     goto f_err;
295                 }
296
297                 if (thisrr->length >
298                     SSL3_BUFFER_get_len(rbuf) - SSL3_RT_HEADER_LENGTH) {
299                     al = SSL_AD_RECORD_OVERFLOW;
300                     SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_PACKET_LENGTH_TOO_LONG);
301                     goto f_err;
302                 }
303             }
304
305             /* now s->rlayer.rstate == SSL_ST_READ_BODY */
306         }
307
308         /*
309          * s->rlayer.rstate == SSL_ST_READ_BODY, get and decode the data.
310          * Calculate how much more data we need to read for the rest of the
311          * record
312          */
313         if (thisrr->rec_version == SSL2_VERSION) {
314             more = thisrr->length + SSL2_RT_HEADER_LENGTH
315                 - SSL3_RT_HEADER_LENGTH;
316         } else {
317             more = thisrr->length;
318         }
319         if (more > 0) {
320             /* now s->packet_length == SSL3_RT_HEADER_LENGTH */
321
322             rret = ssl3_read_n(s, more, more, 1, 0, &n);
323             if (rret <= 0)
324                 return rret;     /* error or non-blocking io */
325         }
326
327         /* set state for later operations */
328         RECORD_LAYER_set_rstate(&s->rlayer, SSL_ST_READ_HEADER);
329
330         /*
331          * At this point, s->packet_length == SSL3_RT_HEADER_LENGTH
332          * + thisrr->length, or s->packet_length == SSL2_RT_HEADER_LENGTH
333          * + thisrr->length and we have that many bytes in s->packet
334          */
335         if (thisrr->rec_version == SSL2_VERSION) {
336             thisrr->input =
337                 &(RECORD_LAYER_get_packet(&s->rlayer)[SSL2_RT_HEADER_LENGTH]);
338         } else {
339             thisrr->input =
340                 &(RECORD_LAYER_get_packet(&s->rlayer)[SSL3_RT_HEADER_LENGTH]);
341         }
342
343         /*
344          * ok, we can now read from 's->packet' data into 'thisrr' thisrr->input
345          * points at thisrr->length bytes, which need to be copied into
346          * thisrr->data by either the decryption or by the decompression When
347          * the data is 'copied' into the thisrr->data buffer, thisrr->input will
348          * be pointed at the new buffer
349          */
350
351         /*
352          * We now have - encrypted [ MAC [ compressed [ plain ] ] ]
353          * thisrr->length bytes of encrypted compressed stuff.
354          */
355
356         /* check is not needed I believe */
357         if (thisrr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
358             al = SSL_AD_RECORD_OVERFLOW;
359             SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
360             goto f_err;
361         }
362
363         /* decrypt in place in 'thisrr->input' */
364         thisrr->data = thisrr->input;
365         thisrr->orig_len = thisrr->length;
366
367         /* Mark this record as not read by upper layers yet */
368         thisrr->read = 0;
369
370         num_recs++;
371
372         /* we have pulled in a full packet so zero things */
373         RECORD_LAYER_reset_packet_length(&s->rlayer);
374         RECORD_LAYER_clear_first_record(&s->rlayer);
375     } while (num_recs < max_recs
376              && thisrr->type == SSL3_RT_APPLICATION_DATA
377              && SSL_USE_EXPLICIT_IV(s)
378              && s->enc_read_ctx != NULL
379              && (EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(s->enc_read_ctx))
380                  & EVP_CIPH_FLAG_PIPELINE)
381              && ssl3_record_app_data_waiting(s));
382
383     /*
384      * If in encrypt-then-mac mode calculate mac from encrypted record. All
385      * the details below are public so no timing details can leak.
386      */
387     if (SSL_READ_ETM(s) && s->read_hash) {
388         unsigned char *mac;
389         /* TODO(size_t): convert this to do size_t properly */
390         imac_size = EVP_MD_CTX_size(s->read_hash);
391         assert(imac_size >= 0 && imac_size <= EVP_MAX_MD_SIZE);
392         if (imac_size < 0 || imac_size > EVP_MAX_MD_SIZE) {
393                 al = SSL_AD_INTERNAL_ERROR;
394                 SSLerr(SSL_F_SSL3_GET_RECORD, ERR_LIB_EVP);
395                 goto f_err;
396         }
397         mac_size = (size_t)imac_size;
398         for (j = 0; j < num_recs; j++) {
399             thisrr = &rr[j];
400
401             if (thisrr->length < mac_size) {
402                 al = SSL_AD_DECODE_ERROR;
403                 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_LENGTH_TOO_SHORT);
404                 goto f_err;
405             }
406             thisrr->length -= mac_size;
407             mac = thisrr->data + thisrr->length;
408             i = s->method->ssl3_enc->mac(s, thisrr, md, 0 /* not send */ );
409             if (i == 0 || CRYPTO_memcmp(md, mac, mac_size) != 0) {
410                 al = SSL_AD_BAD_RECORD_MAC;
411                 SSLerr(SSL_F_SSL3_GET_RECORD,
412                        SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
413                 goto f_err;
414             }
415         }
416     }
417
418     enc_err = s->method->ssl3_enc->enc(s, rr, num_recs, 0);
419
420     /*-
421      * enc_err is:
422      *    0: (in non-constant time) if the record is publicly invalid.
423      *    1: if the padding is valid
424      *    -1: if the padding is invalid
425      */
426     if (enc_err == 0) {
427         if (num_recs == 1 && ossl_statem_skip_early_data(s)) {
428             /*
429              * Valid early_data that we cannot decrypt might fail here as
430              * publicly invalid. We treat it like an empty record.
431              */
432             thisrr = &rr[0];
433             thisrr->length = 0;
434             thisrr->read = 1;
435             RECORD_LAYER_set_numrpipes(&s->rlayer, 1);
436             RECORD_LAYER_reset_read_sequence(&s->rlayer);
437             return 1;
438         }
439         al = SSL_AD_DECRYPTION_FAILED;
440         SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_BLOCK_CIPHER_PAD_IS_WRONG);
441         goto f_err;
442     }
443 #ifdef SSL_DEBUG
444     printf("dec %"OSSLzu"\n", rr[0].length);
445     {
446         size_t z;
447         for (z = 0; z < rr[0].length; z++)
448             printf("%02X%c", rr[0].data[z], ((z + 1) % 16) ? ' ' : '\n');
449     }
450     printf("\n");
451 #endif
452
453     /* r->length is now the compressed data plus mac */
454     if ((sess != NULL) &&
455         (s->enc_read_ctx != NULL) &&
456         (!SSL_READ_ETM(s) && EVP_MD_CTX_md(s->read_hash) != NULL)) {
457         /* s->read_hash != NULL => mac_size != -1 */
458         unsigned char *mac = NULL;
459         unsigned char mac_tmp[EVP_MAX_MD_SIZE];
460
461         mac_size = EVP_MD_CTX_size(s->read_hash);
462         OPENSSL_assert(mac_size <= EVP_MAX_MD_SIZE);
463
464         for (j = 0; j < num_recs; j++) {
465             thisrr = &rr[j];
466             /*
467              * orig_len is the length of the record before any padding was
468              * removed. This is public information, as is the MAC in use,
469              * therefore we can safely process the record in a different amount
470              * of time if it's too short to possibly contain a MAC.
471              */
472             if (thisrr->orig_len < mac_size ||
473                 /* CBC records must have a padding length byte too. */
474                 (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
475                  thisrr->orig_len < mac_size + 1)) {
476                 al = SSL_AD_DECODE_ERROR;
477                 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_LENGTH_TOO_SHORT);
478                 goto f_err;
479             }
480
481             if (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE) {
482                 /*
483                  * We update the length so that the TLS header bytes can be
484                  * constructed correctly but we need to extract the MAC in
485                  * constant time from within the record, without leaking the
486                  * contents of the padding bytes.
487                  */
488                 mac = mac_tmp;
489                 ssl3_cbc_copy_mac(mac_tmp, thisrr, mac_size);
490                 thisrr->length -= mac_size;
491             } else {
492                 /*
493                  * In this case there's no padding, so |rec->orig_len| equals
494                  * |rec->length| and we checked that there's enough bytes for
495                  * |mac_size| above.
496                  */
497                 thisrr->length -= mac_size;
498                 mac = &thisrr->data[thisrr->length];
499             }
500
501             i = s->method->ssl3_enc->mac(s, thisrr, md, 0 /* not send */ );
502             if (i == 0 || mac == NULL
503                 || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0)
504                 enc_err = -1;
505             if (thisrr->length > SSL3_RT_MAX_COMPRESSED_LENGTH + mac_size)
506                 enc_err = -1;
507         }
508     }
509
510     if (enc_err < 0) {
511         if (num_recs == 1 && ossl_statem_skip_early_data(s)) {
512             /*
513              * We assume this is unreadable early_data - we treat it like an
514              * empty record
515              */
516             thisrr = &rr[0];
517             thisrr->length = 0;
518             thisrr->read = 1;
519             RECORD_LAYER_set_numrpipes(&s->rlayer, 1);
520             RECORD_LAYER_reset_read_sequence(&s->rlayer);
521             return 1;
522         }
523         /*
524          * A separate 'decryption_failed' alert was introduced with TLS 1.0,
525          * SSL 3.0 only has 'bad_record_mac'.  But unless a decryption
526          * failure is directly visible from the ciphertext anyway, we should
527          * not reveal which kind of error occurred -- this might become
528          * visible to an attacker (e.g. via a logfile)
529          */
530         al = SSL_AD_BAD_RECORD_MAC;
531         SSLerr(SSL_F_SSL3_GET_RECORD,
532                SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
533         goto f_err;
534     }
535
536     for (j = 0; j < num_recs; j++) {
537         thisrr = &rr[j];
538
539         /* thisrr->length is now just compressed */
540         if (s->expand != NULL) {
541             if (thisrr->length > SSL3_RT_MAX_COMPRESSED_LENGTH) {
542                 al = SSL_AD_RECORD_OVERFLOW;
543                 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_COMPRESSED_LENGTH_TOO_LONG);
544                 goto f_err;
545             }
546             if (!ssl3_do_uncompress(s, thisrr)) {
547                 al = SSL_AD_DECOMPRESSION_FAILURE;
548                 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_BAD_DECOMPRESSION);
549                 goto f_err;
550             }
551         }
552
553         if (SSL_IS_TLS13(s) && s->enc_read_ctx != NULL) {
554             size_t end;
555
556             if (thisrr->length == 0) {
557                 al = SSL_AD_UNEXPECTED_MESSAGE;
558                 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_BAD_RECORD_TYPE);
559                 goto f_err;
560             }
561
562             /* Strip trailing padding */
563             for (end = thisrr->length - 1; end > 0 && thisrr->data[end] == 0;
564                  end--)
565                 continue;
566
567             thisrr->length = end;
568             thisrr->type = thisrr->data[end];
569             if (thisrr->type != SSL3_RT_APPLICATION_DATA
570                     && thisrr->type != SSL3_RT_ALERT
571                     && thisrr->type != SSL3_RT_HANDSHAKE) {
572                 al = SSL_AD_UNEXPECTED_MESSAGE;
573                 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_BAD_RECORD_TYPE);
574                 goto f_err;
575             }
576         }
577
578         if (thisrr->length > SSL3_RT_MAX_PLAIN_LENGTH) {
579             al = SSL_AD_RECORD_OVERFLOW;
580             SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_DATA_LENGTH_TOO_LONG);
581             goto f_err;
582         }
583
584         thisrr->off = 0;
585         /*-
586          * So at this point the following is true
587          * thisrr->type   is the type of record
588          * thisrr->length == number of bytes in record
589          * thisrr->off    == offset to first valid byte
590          * thisrr->data   == where to take bytes from, increment after use :-).
591          */
592
593         /* just read a 0 length packet */
594         if (thisrr->length == 0) {
595             RECORD_LAYER_inc_empty_record_count(&s->rlayer);
596             if (RECORD_LAYER_get_empty_record_count(&s->rlayer)
597                 > MAX_EMPTY_RECORDS) {
598                 al = SSL_AD_UNEXPECTED_MESSAGE;
599                 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_RECORD_TOO_SMALL);
600                 goto f_err;
601             }
602         } else {
603             RECORD_LAYER_reset_empty_record_count(&s->rlayer);
604         }
605     }
606
607     RECORD_LAYER_set_numrpipes(&s->rlayer, num_recs);
608     return 1;
609
610  f_err:
611     ssl3_send_alert(s, SSL3_AL_FATAL, al);
612  err:
613     return ret;
614 }
615
616 int ssl3_do_uncompress(SSL *ssl, SSL3_RECORD *rr)
617 {
618 #ifndef OPENSSL_NO_COMP
619     int i;
620
621     if (rr->comp == NULL) {
622         rr->comp = (unsigned char *)
623             OPENSSL_malloc(SSL3_RT_MAX_ENCRYPTED_LENGTH);
624     }
625     if (rr->comp == NULL)
626         return 0;
627
628     /* TODO(size_t): Convert this call */
629     i = COMP_expand_block(ssl->expand, rr->comp,
630                           SSL3_RT_MAX_PLAIN_LENGTH, rr->data, (int)rr->length);
631     if (i < 0)
632         return 0;
633     else
634         rr->length = i;
635     rr->data = rr->comp;
636 #endif
637     return 1;
638 }
639
640 int ssl3_do_compress(SSL *ssl, SSL3_RECORD *wr)
641 {
642 #ifndef OPENSSL_NO_COMP
643     int i;
644
645     /* TODO(size_t): Convert this call */
646     i = COMP_compress_block(ssl->compress, wr->data,
647                             (int)(wr->length + SSL3_RT_MAX_COMPRESSED_OVERHEAD),
648                             wr->input, (int)wr->length);
649     if (i < 0)
650         return (0);
651     else
652         wr->length = i;
653
654     wr->input = wr->data;
655 #endif
656     return (1);
657 }
658
659 /*-
660  * ssl3_enc encrypts/decrypts |n_recs| records in |inrecs|
661  *
662  * Returns:
663  *   0: (in non-constant time) if the record is publically invalid (i.e. too
664  *       short etc).
665  *   1: if the record's padding is valid / the encryption was successful.
666  *   -1: if the record's padding is invalid or, if sending, an internal error
667  *       occurred.
668  */
669 int ssl3_enc(SSL *s, SSL3_RECORD *inrecs, size_t n_recs, int send)
670 {
671     SSL3_RECORD *rec;
672     EVP_CIPHER_CTX *ds;
673     size_t l, i;
674     size_t bs, mac_size = 0;
675     int imac_size;
676     const EVP_CIPHER *enc;
677
678     rec = inrecs;
679     /*
680      * We shouldn't ever be called with more than one record in the SSLv3 case
681      */
682     if (n_recs != 1)
683         return 0;
684     if (send) {
685         ds = s->enc_write_ctx;
686         if (s->enc_write_ctx == NULL)
687             enc = NULL;
688         else
689             enc = EVP_CIPHER_CTX_cipher(s->enc_write_ctx);
690     } else {
691         ds = s->enc_read_ctx;
692         if (s->enc_read_ctx == NULL)
693             enc = NULL;
694         else
695             enc = EVP_CIPHER_CTX_cipher(s->enc_read_ctx);
696     }
697
698     if ((s->session == NULL) || (ds == NULL) || (enc == NULL)) {
699         memmove(rec->data, rec->input, rec->length);
700         rec->input = rec->data;
701     } else {
702         l = rec->length;
703         /* TODO(size_t): Convert this call */
704         bs = EVP_CIPHER_CTX_block_size(ds);
705
706         /* COMPRESS */
707
708         if ((bs != 1) && send) {
709             i = bs - (l % bs);
710
711             /* we need to add 'i-1' padding bytes */
712             l += i;
713             /*
714              * the last of these zero bytes will be overwritten with the
715              * padding length.
716              */
717             memset(&rec->input[rec->length], 0, i);
718             rec->length += i;
719             rec->input[l - 1] = (unsigned char)(i - 1);
720         }
721
722         if (!send) {
723             if (l == 0 || l % bs != 0)
724                 return 0;
725             /* otherwise, rec->length >= bs */
726         }
727
728         /* TODO(size_t): Convert this call */
729         if (EVP_Cipher(ds, rec->data, rec->input, (unsigned int)l) < 1)
730             return -1;
731
732         if (EVP_MD_CTX_md(s->read_hash) != NULL) {
733             /* TODO(size_t): convert me */
734             imac_size = EVP_MD_CTX_size(s->read_hash);
735             if (imac_size < 0)
736                 return -1;
737             mac_size = (size_t)imac_size;
738         }
739         if ((bs != 1) && !send)
740             return ssl3_cbc_remove_padding(rec, bs, mac_size);
741     }
742     return (1);
743 }
744
745 #define MAX_PADDING 256
746 /*-
747  * tls1_enc encrypts/decrypts |n_recs| in |recs|.
748  *
749  * Returns:
750  *   0: (in non-constant time) if the record is publically invalid (i.e. too
751  *       short etc).
752  *   1: if the record's padding is valid / the encryption was successful.
753  *   -1: if the record's padding/AEAD-authenticator is invalid or, if sending,
754  *       an internal error occurred.
755  */
756 int tls1_enc(SSL *s, SSL3_RECORD *recs, size_t n_recs, int send)
757 {
758     EVP_CIPHER_CTX *ds;
759     size_t reclen[SSL_MAX_PIPELINES];
760     unsigned char buf[SSL_MAX_PIPELINES][EVP_AEAD_TLS1_AAD_LEN];
761     int i, pad = 0, ret, tmpr;
762     size_t bs, mac_size = 0, ctr, padnum, loop;
763     unsigned char padval;
764     int imac_size;
765     const EVP_CIPHER *enc;
766
767     if (n_recs == 0)
768         return 0;
769
770     if (send) {
771         if (EVP_MD_CTX_md(s->write_hash)) {
772             int n = EVP_MD_CTX_size(s->write_hash);
773             OPENSSL_assert(n >= 0);
774         }
775         ds = s->enc_write_ctx;
776         if (s->enc_write_ctx == NULL)
777             enc = NULL;
778         else {
779             int ivlen;
780             enc = EVP_CIPHER_CTX_cipher(s->enc_write_ctx);
781             /* For TLSv1.1 and later explicit IV */
782             if (SSL_USE_EXPLICIT_IV(s)
783                 && EVP_CIPHER_mode(enc) == EVP_CIPH_CBC_MODE)
784                 ivlen = EVP_CIPHER_iv_length(enc);
785             else
786                 ivlen = 0;
787             if (ivlen > 1) {
788                 for (ctr = 0; ctr < n_recs; ctr++) {
789                     if (recs[ctr].data != recs[ctr].input) {
790                         /*
791                          * we can't write into the input stream: Can this ever
792                          * happen?? (steve)
793                          */
794                         SSLerr(SSL_F_TLS1_ENC, ERR_R_INTERNAL_ERROR);
795                         return -1;
796                     } else if (RAND_bytes(recs[ctr].input, ivlen) <= 0) {
797                         SSLerr(SSL_F_TLS1_ENC, ERR_R_INTERNAL_ERROR);
798                         return -1;
799                     }
800                 }
801             }
802         }
803     } else {
804         if (EVP_MD_CTX_md(s->read_hash)) {
805             int n = EVP_MD_CTX_size(s->read_hash);
806             OPENSSL_assert(n >= 0);
807         }
808         ds = s->enc_read_ctx;
809         if (s->enc_read_ctx == NULL)
810             enc = NULL;
811         else
812             enc = EVP_CIPHER_CTX_cipher(s->enc_read_ctx);
813     }
814
815     if ((s->session == NULL) || (ds == NULL) || (enc == NULL)) {
816         for (ctr = 0; ctr < n_recs; ctr++) {
817             memmove(recs[ctr].data, recs[ctr].input, recs[ctr].length);
818             recs[ctr].input = recs[ctr].data;
819         }
820         ret = 1;
821     } else {
822         bs = EVP_CIPHER_block_size(EVP_CIPHER_CTX_cipher(ds));
823
824         if (n_recs > 1) {
825             if (!(EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(ds))
826                   & EVP_CIPH_FLAG_PIPELINE)) {
827                 /*
828                  * We shouldn't have been called with pipeline data if the
829                  * cipher doesn't support pipelining
830                  */
831                 SSLerr(SSL_F_TLS1_ENC, SSL_R_PIPELINE_FAILURE);
832                 return -1;
833             }
834         }
835         for (ctr = 0; ctr < n_recs; ctr++) {
836             reclen[ctr] = recs[ctr].length;
837
838             if (EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(ds))
839                 & EVP_CIPH_FLAG_AEAD_CIPHER) {
840                 unsigned char *seq;
841
842                 seq = send ? RECORD_LAYER_get_write_sequence(&s->rlayer)
843                     : RECORD_LAYER_get_read_sequence(&s->rlayer);
844
845                 if (SSL_IS_DTLS(s)) {
846                     /* DTLS does not support pipelining */
847                     unsigned char dtlsseq[9], *p = dtlsseq;
848
849                     s2n(send ? DTLS_RECORD_LAYER_get_w_epoch(&s->rlayer) :
850                         DTLS_RECORD_LAYER_get_r_epoch(&s->rlayer), p);
851                     memcpy(p, &seq[2], 6);
852                     memcpy(buf[ctr], dtlsseq, 8);
853                 } else {
854                     memcpy(buf[ctr], seq, 8);
855                     for (i = 7; i >= 0; i--) { /* increment */
856                         ++seq[i];
857                         if (seq[i] != 0)
858                             break;
859                     }
860                 }
861
862                 buf[ctr][8] = recs[ctr].type;
863                 buf[ctr][9] = (unsigned char)(s->version >> 8);
864                 buf[ctr][10] = (unsigned char)(s->version);
865                 buf[ctr][11] = (unsigned char)(recs[ctr].length >> 8);
866                 buf[ctr][12] = (unsigned char)(recs[ctr].length & 0xff);
867                 pad = EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_AEAD_TLS1_AAD,
868                                           EVP_AEAD_TLS1_AAD_LEN, buf[ctr]);
869                 if (pad <= 0)
870                     return -1;
871
872                 if (send) {
873                     reclen[ctr] += pad;
874                     recs[ctr].length += pad;
875                 }
876
877             } else if ((bs != 1) && send) {
878                 padnum = bs - (reclen[ctr] % bs);
879
880                 /* Add weird padding of upto 256 bytes */
881
882                 if (padnum > MAX_PADDING)
883                     return -1;
884                 /* we need to add 'padnum' padding bytes of value padval */
885                 padval = (unsigned char)(padnum - 1);
886                 for (loop = reclen[ctr]; loop < reclen[ctr] + padnum; loop++)
887                     recs[ctr].input[loop] = padval;
888                 reclen[ctr] += padnum;
889                 recs[ctr].length += padnum;
890             }
891
892             if (!send) {
893                 if (reclen[ctr] == 0 || reclen[ctr] % bs != 0)
894                     return 0;
895             }
896         }
897         if (n_recs > 1) {
898             unsigned char *data[SSL_MAX_PIPELINES];
899
900             /* Set the output buffers */
901             for (ctr = 0; ctr < n_recs; ctr++) {
902                 data[ctr] = recs[ctr].data;
903             }
904             if (EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_SET_PIPELINE_OUTPUT_BUFS,
905                                     (int)n_recs, data) <= 0) {
906                 SSLerr(SSL_F_TLS1_ENC, SSL_R_PIPELINE_FAILURE);
907             }
908             /* Set the input buffers */
909             for (ctr = 0; ctr < n_recs; ctr++) {
910                 data[ctr] = recs[ctr].input;
911             }
912             if (EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_SET_PIPELINE_INPUT_BUFS,
913                                     (int)n_recs, data) <= 0
914                 || EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_SET_PIPELINE_INPUT_LENS,
915                                        (int)n_recs, reclen) <= 0) {
916                 SSLerr(SSL_F_TLS1_ENC, SSL_R_PIPELINE_FAILURE);
917                 return -1;
918             }
919         }
920
921         /* TODO(size_t): Convert this call */
922         tmpr = EVP_Cipher(ds, recs[0].data, recs[0].input,
923                           (unsigned int)reclen[0]);
924         if ((EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(ds))
925              & EVP_CIPH_FLAG_CUSTOM_CIPHER)
926             ? (tmpr < 0)
927             : (tmpr == 0))
928             return -1;          /* AEAD can fail to verify MAC */
929         if (send == 0) {
930             if (EVP_CIPHER_mode(enc) == EVP_CIPH_GCM_MODE) {
931                 for (ctr = 0; ctr < n_recs; ctr++) {
932                     recs[ctr].data += EVP_GCM_TLS_EXPLICIT_IV_LEN;
933                     recs[ctr].input += EVP_GCM_TLS_EXPLICIT_IV_LEN;
934                     recs[ctr].length -= EVP_GCM_TLS_EXPLICIT_IV_LEN;
935                 }
936             } else if (EVP_CIPHER_mode(enc) == EVP_CIPH_CCM_MODE) {
937                 for (ctr = 0; ctr < n_recs; ctr++) {
938                     recs[ctr].data += EVP_CCM_TLS_EXPLICIT_IV_LEN;
939                     recs[ctr].input += EVP_CCM_TLS_EXPLICIT_IV_LEN;
940                     recs[ctr].length -= EVP_CCM_TLS_EXPLICIT_IV_LEN;
941                 }
942             }
943         }
944
945         ret = 1;
946         if (!SSL_READ_ETM(s) && EVP_MD_CTX_md(s->read_hash) != NULL) {
947             imac_size = EVP_MD_CTX_size(s->read_hash);
948             if (imac_size < 0)
949                 return -1;
950             mac_size = (size_t)imac_size;
951         }
952         if ((bs != 1) && !send) {
953             int tmpret;
954             for (ctr = 0; ctr < n_recs; ctr++) {
955                 tmpret = tls1_cbc_remove_padding(s, &recs[ctr], bs, mac_size);
956                 /*
957                  * If tmpret == 0 then this means publicly invalid so we can
958                  * short circuit things here. Otherwise we must respect constant
959                  * time behaviour.
960                  */
961                 if (tmpret == 0)
962                     return 0;
963                 ret = constant_time_select_int(constant_time_eq_int(tmpret, 1),
964                                                ret, -1);
965             }
966         }
967         if (pad && !send) {
968             for (ctr = 0; ctr < n_recs; ctr++) {
969                 recs[ctr].length -= pad;
970             }
971         }
972     }
973     return ret;
974 }
975
976 int n_ssl3_mac(SSL *ssl, SSL3_RECORD *rec, unsigned char *md, int send)
977 {
978     unsigned char *mac_sec, *seq;
979     const EVP_MD_CTX *hash;
980     unsigned char *p, rec_char;
981     size_t md_size;
982     size_t npad;
983     int t;
984
985     if (send) {
986         mac_sec = &(ssl->s3->write_mac_secret[0]);
987         seq = RECORD_LAYER_get_write_sequence(&ssl->rlayer);
988         hash = ssl->write_hash;
989     } else {
990         mac_sec = &(ssl->s3->read_mac_secret[0]);
991         seq = RECORD_LAYER_get_read_sequence(&ssl->rlayer);
992         hash = ssl->read_hash;
993     }
994
995     t = EVP_MD_CTX_size(hash);
996     if (t < 0)
997         return 0;
998     md_size = t;
999     npad = (48 / md_size) * md_size;
1000
1001     if (!send &&
1002         EVP_CIPHER_CTX_mode(ssl->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
1003         ssl3_cbc_record_digest_supported(hash)) {
1004         /*
1005          * This is a CBC-encrypted record. We must avoid leaking any
1006          * timing-side channel information about how many blocks of data we
1007          * are hashing because that gives an attacker a timing-oracle.
1008          */
1009
1010         /*-
1011          * npad is, at most, 48 bytes and that's with MD5:
1012          *   16 + 48 + 8 (sequence bytes) + 1 + 2 = 75.
1013          *
1014          * With SHA-1 (the largest hash speced for SSLv3) the hash size
1015          * goes up 4, but npad goes down by 8, resulting in a smaller
1016          * total size.
1017          */
1018         unsigned char header[75];
1019         size_t j = 0;
1020         memcpy(header + j, mac_sec, md_size);
1021         j += md_size;
1022         memcpy(header + j, ssl3_pad_1, npad);
1023         j += npad;
1024         memcpy(header + j, seq, 8);
1025         j += 8;
1026         header[j++] = rec->type;
1027         header[j++] = (unsigned char)(rec->length >> 8);
1028         header[j++] = (unsigned char)(rec->length & 0xff);
1029
1030         /* Final param == is SSLv3 */
1031         if (ssl3_cbc_digest_record(hash,
1032                                    md, &md_size,
1033                                    header, rec->input,
1034                                    rec->length + md_size, rec->orig_len,
1035                                    mac_sec, md_size, 1) <= 0)
1036             return 0;
1037     } else {
1038         unsigned int md_size_u;
1039         /* Chop the digest off the end :-) */
1040         EVP_MD_CTX *md_ctx = EVP_MD_CTX_new();
1041
1042         if (md_ctx == NULL)
1043             return 0;
1044
1045         rec_char = rec->type;
1046         p = md;
1047         s2n(rec->length, p);
1048         if (EVP_MD_CTX_copy_ex(md_ctx, hash) <= 0
1049             || EVP_DigestUpdate(md_ctx, mac_sec, md_size) <= 0
1050             || EVP_DigestUpdate(md_ctx, ssl3_pad_1, npad) <= 0
1051             || EVP_DigestUpdate(md_ctx, seq, 8) <= 0
1052             || EVP_DigestUpdate(md_ctx, &rec_char, 1) <= 0
1053             || EVP_DigestUpdate(md_ctx, md, 2) <= 0
1054             || EVP_DigestUpdate(md_ctx, rec->input, rec->length) <= 0
1055             || EVP_DigestFinal_ex(md_ctx, md, NULL) <= 0
1056             || EVP_MD_CTX_copy_ex(md_ctx, hash) <= 0
1057             || EVP_DigestUpdate(md_ctx, mac_sec, md_size) <= 0
1058             || EVP_DigestUpdate(md_ctx, ssl3_pad_2, npad) <= 0
1059             || EVP_DigestUpdate(md_ctx, md, md_size) <= 0
1060             || EVP_DigestFinal_ex(md_ctx, md, &md_size_u) <= 0) {
1061             EVP_MD_CTX_reset(md_ctx);
1062             return 0;
1063         }
1064
1065         EVP_MD_CTX_free(md_ctx);
1066     }
1067
1068     ssl3_record_sequence_update(seq);
1069     return 1;
1070 }
1071
1072 int tls1_mac(SSL *ssl, SSL3_RECORD *rec, unsigned char *md, int send)
1073 {
1074     unsigned char *seq;
1075     EVP_MD_CTX *hash;
1076     size_t md_size;
1077     int i;
1078     EVP_MD_CTX *hmac = NULL, *mac_ctx;
1079     unsigned char header[13];
1080     int stream_mac = (send ? (ssl->mac_flags & SSL_MAC_FLAG_WRITE_MAC_STREAM)
1081                       : (ssl->mac_flags & SSL_MAC_FLAG_READ_MAC_STREAM));
1082     int t;
1083
1084     if (send) {
1085         seq = RECORD_LAYER_get_write_sequence(&ssl->rlayer);
1086         hash = ssl->write_hash;
1087     } else {
1088         seq = RECORD_LAYER_get_read_sequence(&ssl->rlayer);
1089         hash = ssl->read_hash;
1090     }
1091
1092     t = EVP_MD_CTX_size(hash);
1093     OPENSSL_assert(t >= 0);
1094     md_size = t;
1095
1096     /* I should fix this up TLS TLS TLS TLS TLS XXXXXXXX */
1097     if (stream_mac) {
1098         mac_ctx = hash;
1099     } else {
1100         hmac = EVP_MD_CTX_new();
1101         if (hmac == NULL || !EVP_MD_CTX_copy(hmac, hash))
1102             return 0;
1103         mac_ctx = hmac;
1104     }
1105
1106     if (SSL_IS_DTLS(ssl)) {
1107         unsigned char dtlsseq[8], *p = dtlsseq;
1108
1109         s2n(send ? DTLS_RECORD_LAYER_get_w_epoch(&ssl->rlayer) :
1110             DTLS_RECORD_LAYER_get_r_epoch(&ssl->rlayer), p);
1111         memcpy(p, &seq[2], 6);
1112
1113         memcpy(header, dtlsseq, 8);
1114     } else
1115         memcpy(header, seq, 8);
1116
1117     header[8] = rec->type;
1118     header[9] = (unsigned char)(ssl->version >> 8);
1119     header[10] = (unsigned char)(ssl->version);
1120     header[11] = (unsigned char)(rec->length >> 8);
1121     header[12] = (unsigned char)(rec->length & 0xff);
1122
1123     if (!send && !SSL_READ_ETM(ssl) &&
1124         EVP_CIPHER_CTX_mode(ssl->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
1125         ssl3_cbc_record_digest_supported(mac_ctx)) {
1126         /*
1127          * This is a CBC-encrypted record. We must avoid leaking any
1128          * timing-side channel information about how many blocks of data we
1129          * are hashing because that gives an attacker a timing-oracle.
1130          */
1131         /* Final param == not SSLv3 */
1132         if (ssl3_cbc_digest_record(mac_ctx,
1133                                    md, &md_size,
1134                                    header, rec->input,
1135                                    rec->length + md_size, rec->orig_len,
1136                                    ssl->s3->read_mac_secret,
1137                                    ssl->s3->read_mac_secret_size, 0) <= 0) {
1138             EVP_MD_CTX_free(hmac);
1139             return -1;
1140         }
1141     } else {
1142         /* TODO(size_t): Convert these calls */
1143         if (EVP_DigestSignUpdate(mac_ctx, header, sizeof(header)) <= 0
1144             || EVP_DigestSignUpdate(mac_ctx, rec->input, rec->length) <= 0
1145             || EVP_DigestSignFinal(mac_ctx, md, &md_size) <= 0) {
1146             EVP_MD_CTX_free(hmac);
1147             return 0;
1148         }
1149     }
1150
1151     EVP_MD_CTX_free(hmac);
1152
1153 #ifdef SSL_DEBUG
1154     fprintf(stderr, "seq=");
1155     {
1156         int z;
1157         for (z = 0; z < 8; z++)
1158             fprintf(stderr, "%02X ", seq[z]);
1159         fprintf(stderr, "\n");
1160     }
1161     fprintf(stderr, "rec=");
1162     {
1163         size_t z;
1164         for (z = 0; z < rec->length; z++)
1165             fprintf(stderr, "%02X ", rec->data[z]);
1166         fprintf(stderr, "\n");
1167     }
1168 #endif
1169
1170     if (!SSL_IS_DTLS(ssl)) {
1171         for (i = 7; i >= 0; i--) {
1172             ++seq[i];
1173             if (seq[i] != 0)
1174                 break;
1175         }
1176     }
1177 #ifdef SSL_DEBUG
1178     {
1179         unsigned int z;
1180         for (z = 0; z < md_size; z++)
1181             fprintf(stderr, "%02X ", md[z]);
1182         fprintf(stderr, "\n");
1183     }
1184 #endif
1185     return 1;
1186 }
1187
1188 /*-
1189  * ssl3_cbc_remove_padding removes padding from the decrypted, SSLv3, CBC
1190  * record in |rec| by updating |rec->length| in constant time.
1191  *
1192  * block_size: the block size of the cipher used to encrypt the record.
1193  * returns:
1194  *   0: (in non-constant time) if the record is publicly invalid.
1195  *   1: if the padding was valid
1196  *  -1: otherwise.
1197  */
1198 int ssl3_cbc_remove_padding(SSL3_RECORD *rec,
1199                             size_t block_size, size_t mac_size)
1200 {
1201     size_t padding_length;
1202     size_t good;
1203     const size_t overhead = 1 /* padding length byte */  + mac_size;
1204
1205     /*
1206      * These lengths are all public so we can test them in non-constant time.
1207      */
1208     if (overhead > rec->length)
1209         return 0;
1210
1211     padding_length = rec->data[rec->length - 1];
1212     good = constant_time_ge_s(rec->length, padding_length + overhead);
1213     /* SSLv3 requires that the padding is minimal. */
1214     good &= constant_time_ge_s(block_size, padding_length + 1);
1215     rec->length -= good & (padding_length + 1);
1216     return constant_time_select_int_s(good, 1, -1);
1217 }
1218
1219 /*-
1220  * tls1_cbc_remove_padding removes the CBC padding from the decrypted, TLS, CBC
1221  * record in |rec| in constant time and returns 1 if the padding is valid and
1222  * -1 otherwise. It also removes any explicit IV from the start of the record
1223  * without leaking any timing about whether there was enough space after the
1224  * padding was removed.
1225  *
1226  * block_size: the block size of the cipher used to encrypt the record.
1227  * returns:
1228  *   0: (in non-constant time) if the record is publicly invalid.
1229  *   1: if the padding was valid
1230  *  -1: otherwise.
1231  */
1232 int tls1_cbc_remove_padding(const SSL *s,
1233                             SSL3_RECORD *rec,
1234                             size_t block_size, size_t mac_size)
1235 {
1236     size_t good;
1237     size_t padding_length, to_check, i;
1238     const size_t overhead = 1 /* padding length byte */  + mac_size;
1239     /* Check if version requires explicit IV */
1240     if (SSL_USE_EXPLICIT_IV(s)) {
1241         /*
1242          * These lengths are all public so we can test them in non-constant
1243          * time.
1244          */
1245         if (overhead + block_size > rec->length)
1246             return 0;
1247         /* We can now safely skip explicit IV */
1248         rec->data += block_size;
1249         rec->input += block_size;
1250         rec->length -= block_size;
1251         rec->orig_len -= block_size;
1252     } else if (overhead > rec->length)
1253         return 0;
1254
1255     padding_length = rec->data[rec->length - 1];
1256
1257     if (EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(s->enc_read_ctx)) &
1258         EVP_CIPH_FLAG_AEAD_CIPHER) {
1259         /* padding is already verified */
1260         rec->length -= padding_length + 1;
1261         return 1;
1262     }
1263
1264     good = constant_time_ge_s(rec->length, overhead + padding_length);
1265     /*
1266      * The padding consists of a length byte at the end of the record and
1267      * then that many bytes of padding, all with the same value as the length
1268      * byte. Thus, with the length byte included, there are i+1 bytes of
1269      * padding. We can't check just |padding_length+1| bytes because that
1270      * leaks decrypted information. Therefore we always have to check the
1271      * maximum amount of padding possible. (Again, the length of the record
1272      * is public information so we can use it.)
1273      */
1274     to_check = 256;            /* maximum amount of padding, inc length byte. */
1275     if (to_check > rec->length)
1276         to_check = rec->length;
1277
1278     for (i = 0; i < to_check; i++) {
1279         unsigned char mask = constant_time_ge_8_s(padding_length, i);
1280         unsigned char b = rec->data[rec->length - 1 - i];
1281         /*
1282          * The final |padding_length+1| bytes should all have the value
1283          * |padding_length|. Therefore the XOR should be zero.
1284          */
1285         good &= ~(mask & (padding_length ^ b));
1286     }
1287
1288     /*
1289      * If any of the final |padding_length+1| bytes had the wrong value, one
1290      * or more of the lower eight bits of |good| will be cleared.
1291      */
1292     good = constant_time_eq_s(0xff, good & 0xff);
1293     rec->length -= good & (padding_length + 1);
1294
1295     return constant_time_select_int_s(good, 1, -1);
1296 }
1297
1298 /*-
1299  * ssl3_cbc_copy_mac copies |md_size| bytes from the end of |rec| to |out| in
1300  * constant time (independent of the concrete value of rec->length, which may
1301  * vary within a 256-byte window).
1302  *
1303  * ssl3_cbc_remove_padding or tls1_cbc_remove_padding must be called prior to
1304  * this function.
1305  *
1306  * On entry:
1307  *   rec->orig_len >= md_size
1308  *   md_size <= EVP_MAX_MD_SIZE
1309  *
1310  * If CBC_MAC_ROTATE_IN_PLACE is defined then the rotation is performed with
1311  * variable accesses in a 64-byte-aligned buffer. Assuming that this fits into
1312  * a single or pair of cache-lines, then the variable memory accesses don't
1313  * actually affect the timing. CPUs with smaller cache-lines [if any] are
1314  * not multi-core and are not considered vulnerable to cache-timing attacks.
1315  */
1316 #define CBC_MAC_ROTATE_IN_PLACE
1317
1318 void ssl3_cbc_copy_mac(unsigned char *out,
1319                        const SSL3_RECORD *rec, size_t md_size)
1320 {
1321 #if defined(CBC_MAC_ROTATE_IN_PLACE)
1322     unsigned char rotated_mac_buf[64 + EVP_MAX_MD_SIZE];
1323     unsigned char *rotated_mac;
1324 #else
1325     unsigned char rotated_mac[EVP_MAX_MD_SIZE];
1326 #endif
1327
1328     /*
1329      * mac_end is the index of |rec->data| just after the end of the MAC.
1330      */
1331     size_t mac_end = rec->length;
1332     size_t mac_start = mac_end - md_size;
1333     size_t in_mac;
1334     /*
1335      * scan_start contains the number of bytes that we can ignore because the
1336      * MAC's position can only vary by 255 bytes.
1337      */
1338     size_t scan_start = 0;
1339     size_t i, j;
1340     size_t rotate_offset;
1341
1342     OPENSSL_assert(rec->orig_len >= md_size);
1343     OPENSSL_assert(md_size <= EVP_MAX_MD_SIZE);
1344
1345 #if defined(CBC_MAC_ROTATE_IN_PLACE)
1346     rotated_mac = rotated_mac_buf + ((0 - (size_t)rotated_mac_buf) & 63);
1347 #endif
1348
1349     /* This information is public so it's safe to branch based on it. */
1350     if (rec->orig_len > md_size + 255 + 1)
1351         scan_start = rec->orig_len - (md_size + 255 + 1);
1352
1353     in_mac = 0;
1354     rotate_offset = 0;
1355     memset(rotated_mac, 0, md_size);
1356     for (i = scan_start, j = 0; i < rec->orig_len; i++) {
1357         size_t mac_started = constant_time_eq_s(i, mac_start);
1358         size_t mac_ended = constant_time_lt_s(i, mac_end);
1359         unsigned char b = rec->data[i];
1360
1361         in_mac |= mac_started;
1362         in_mac &= mac_ended;
1363         rotate_offset |= j & mac_started;
1364         rotated_mac[j++] |= b & in_mac;
1365         j &= constant_time_lt_s(j, md_size);
1366     }
1367
1368     /* Now rotate the MAC */
1369 #if defined(CBC_MAC_ROTATE_IN_PLACE)
1370     j = 0;
1371     for (i = 0; i < md_size; i++) {
1372         /* in case cache-line is 32 bytes, touch second line */
1373         ((volatile unsigned char *)rotated_mac)[rotate_offset ^ 32];
1374         out[j++] = rotated_mac[rotate_offset++];
1375         rotate_offset &= constant_time_lt_s(rotate_offset, md_size);
1376     }
1377 #else
1378     memset(out, 0, md_size);
1379     rotate_offset = md_size - rotate_offset;
1380     rotate_offset &= constant_time_lt_s(rotate_offset, md_size);
1381     for (i = 0; i < md_size; i++) {
1382         for (j = 0; j < md_size; j++)
1383             out[j] |= rotated_mac[i] & constant_time_eq_8_s(j, rotate_offset);
1384         rotate_offset++;
1385         rotate_offset &= constant_time_lt_s(rotate_offset, md_size);
1386     }
1387 #endif
1388 }
1389
1390 int dtls1_process_record(SSL *s, DTLS1_BITMAP *bitmap)
1391 {
1392     int i, al;
1393     int enc_err;
1394     SSL_SESSION *sess;
1395     SSL3_RECORD *rr;
1396     int imac_size;
1397     size_t mac_size;
1398     unsigned char md[EVP_MAX_MD_SIZE];
1399
1400     rr = RECORD_LAYER_get_rrec(&s->rlayer);
1401     sess = s->session;
1402
1403     /*
1404      * At this point, s->packet_length == SSL3_RT_HEADER_LNGTH + rr->length,
1405      * and we have that many bytes in s->packet
1406      */
1407     rr->input = &(RECORD_LAYER_get_packet(&s->rlayer)[DTLS1_RT_HEADER_LENGTH]);
1408
1409     /*
1410      * ok, we can now read from 's->packet' data into 'rr' rr->input points
1411      * at rr->length bytes, which need to be copied into rr->data by either
1412      * the decryption or by the decompression When the data is 'copied' into
1413      * the rr->data buffer, rr->input will be pointed at the new buffer
1414      */
1415
1416     /*
1417      * We now have - encrypted [ MAC [ compressed [ plain ] ] ] rr->length
1418      * bytes of encrypted compressed stuff.
1419      */
1420
1421     /* check is not needed I believe */
1422     if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
1423         al = SSL_AD_RECORD_OVERFLOW;
1424         SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
1425         goto f_err;
1426     }
1427
1428     /* decrypt in place in 'rr->input' */
1429     rr->data = rr->input;
1430     rr->orig_len = rr->length;
1431
1432     if (SSL_READ_ETM(s) && s->read_hash) {
1433         unsigned char *mac;
1434         mac_size = EVP_MD_CTX_size(s->read_hash);
1435         OPENSSL_assert(mac_size <= EVP_MAX_MD_SIZE);
1436         if (rr->orig_len < mac_size) {
1437             al = SSL_AD_DECODE_ERROR;
1438             SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_LENGTH_TOO_SHORT);
1439             goto f_err;
1440         }
1441         rr->length -= mac_size;
1442         mac = rr->data + rr->length;
1443         i = s->method->ssl3_enc->mac(s, rr, md, 0 /* not send */ );
1444         if (i == 0 || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0) {
1445             al = SSL_AD_BAD_RECORD_MAC;
1446             SSLerr(SSL_F_DTLS1_PROCESS_RECORD,
1447                    SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
1448             goto f_err;
1449         }
1450     }
1451
1452     enc_err = s->method->ssl3_enc->enc(s, rr, 1, 0);
1453     /*-
1454      * enc_err is:
1455      *    0: (in non-constant time) if the record is publically invalid.
1456      *    1: if the padding is valid
1457      *   -1: if the padding is invalid
1458      */
1459     if (enc_err == 0) {
1460         /* For DTLS we simply ignore bad packets. */
1461         rr->length = 0;
1462         RECORD_LAYER_reset_packet_length(&s->rlayer);
1463         goto err;
1464     }
1465 #ifdef SSL_DEBUG
1466     printf("dec %ld\n", rr->length);
1467     {
1468         size_t z;
1469         for (z = 0; z < rr->length; z++)
1470             printf("%02X%c", rr->data[z], ((z + 1) % 16) ? ' ' : '\n');
1471     }
1472     printf("\n");
1473 #endif
1474
1475     /* r->length is now the compressed data plus mac */
1476     if ((sess != NULL) && !SSL_READ_ETM(s) &&
1477         (s->enc_read_ctx != NULL) && (EVP_MD_CTX_md(s->read_hash) != NULL)) {
1478         /* s->read_hash != NULL => mac_size != -1 */
1479         unsigned char *mac = NULL;
1480         unsigned char mac_tmp[EVP_MAX_MD_SIZE];
1481
1482         /* TODO(size_t): Convert this to do size_t properly */
1483         imac_size = EVP_MD_CTX_size(s->read_hash);
1484         if (imac_size < 0) {
1485             al = SSL_AD_INTERNAL_ERROR;
1486             SSLerr(SSL_F_DTLS1_PROCESS_RECORD, ERR_LIB_EVP);
1487             goto f_err;
1488         }
1489         mac_size = (size_t)imac_size;
1490         OPENSSL_assert(mac_size <= EVP_MAX_MD_SIZE);
1491
1492         /*
1493          * orig_len is the length of the record before any padding was
1494          * removed. This is public information, as is the MAC in use,
1495          * therefore we can safely process the record in a different amount
1496          * of time if it's too short to possibly contain a MAC.
1497          */
1498         if (rr->orig_len < mac_size ||
1499             /* CBC records must have a padding length byte too. */
1500             (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
1501              rr->orig_len < mac_size + 1)) {
1502             al = SSL_AD_DECODE_ERROR;
1503             SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_LENGTH_TOO_SHORT);
1504             goto f_err;
1505         }
1506
1507         if (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE) {
1508             /*
1509              * We update the length so that the TLS header bytes can be
1510              * constructed correctly but we need to extract the MAC in
1511              * constant time from within the record, without leaking the
1512              * contents of the padding bytes.
1513              */
1514             mac = mac_tmp;
1515             ssl3_cbc_copy_mac(mac_tmp, rr, mac_size);
1516             rr->length -= mac_size;
1517         } else {
1518             /*
1519              * In this case there's no padding, so |rec->orig_len| equals
1520              * |rec->length| and we checked that there's enough bytes for
1521              * |mac_size| above.
1522              */
1523             rr->length -= mac_size;
1524             mac = &rr->data[rr->length];
1525         }
1526
1527         i = s->method->ssl3_enc->mac(s, rr, md, 0 /* not send */ );
1528         if (i == 0 || mac == NULL
1529             || CRYPTO_memcmp(md, mac, mac_size) != 0)
1530             enc_err = -1;
1531         if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH + mac_size)
1532             enc_err = -1;
1533     }
1534
1535     if (enc_err < 0) {
1536         /* decryption failed, silently discard message */
1537         rr->length = 0;
1538         RECORD_LAYER_reset_packet_length(&s->rlayer);
1539         goto err;
1540     }
1541
1542     /* r->length is now just compressed */
1543     if (s->expand != NULL) {
1544         if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH) {
1545             al = SSL_AD_RECORD_OVERFLOW;
1546             SSLerr(SSL_F_DTLS1_PROCESS_RECORD,
1547                    SSL_R_COMPRESSED_LENGTH_TOO_LONG);
1548             goto f_err;
1549         }
1550         if (!ssl3_do_uncompress(s, rr)) {
1551             al = SSL_AD_DECOMPRESSION_FAILURE;
1552             SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_BAD_DECOMPRESSION);
1553             goto f_err;
1554         }
1555     }
1556
1557     if (rr->length > SSL3_RT_MAX_PLAIN_LENGTH) {
1558         al = SSL_AD_RECORD_OVERFLOW;
1559         SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_DATA_LENGTH_TOO_LONG);
1560         goto f_err;
1561     }
1562
1563     rr->off = 0;
1564     /*-
1565      * So at this point the following is true
1566      * ssl->s3->rrec.type   is the type of record
1567      * ssl->s3->rrec.length == number of bytes in record
1568      * ssl->s3->rrec.off    == offset to first valid byte
1569      * ssl->s3->rrec.data   == where to take bytes from, increment
1570      *                         after use :-).
1571      */
1572
1573     /* we have pulled in a full packet so zero things */
1574     RECORD_LAYER_reset_packet_length(&s->rlayer);
1575
1576     /* Mark receipt of record. */
1577     dtls1_record_bitmap_update(s, bitmap);
1578
1579     return (1);
1580
1581  f_err:
1582     ssl3_send_alert(s, SSL3_AL_FATAL, al);
1583  err:
1584     return (0);
1585 }
1586
1587 /*
1588  * retrieve a buffered record that belongs to the current epoch, ie,
1589  * processed
1590  */
1591 #define dtls1_get_processed_record(s) \
1592                    dtls1_retrieve_buffered_record((s), \
1593                    &(DTLS_RECORD_LAYER_get_processed_rcds(&s->rlayer)))
1594
1595 /*-
1596  * Call this to get a new input record.
1597  * It will return <= 0 if more data is needed, normally due to an error
1598  * or non-blocking IO.
1599  * When it finishes, one packet has been decoded and can be found in
1600  * ssl->s3->rrec.type    - is the type of record
1601  * ssl->s3->rrec.data,   - data
1602  * ssl->s3->rrec.length, - number of bytes
1603  */
1604 /* used only by dtls1_read_bytes */
1605 int dtls1_get_record(SSL *s)
1606 {
1607     int ssl_major, ssl_minor;
1608     int rret;
1609     size_t more, n;
1610     SSL3_RECORD *rr;
1611     unsigned char *p = NULL;
1612     unsigned short version;
1613     DTLS1_BITMAP *bitmap;
1614     unsigned int is_next_epoch;
1615
1616     rr = RECORD_LAYER_get_rrec(&s->rlayer);
1617
1618  again:
1619     /*
1620      * The epoch may have changed.  If so, process all the pending records.
1621      * This is a non-blocking operation.
1622      */
1623     if (!dtls1_process_buffered_records(s))
1624         return -1;
1625
1626     /* if we're renegotiating, then there may be buffered records */
1627     if (dtls1_get_processed_record(s))
1628         return 1;
1629
1630     /* get something from the wire */
1631
1632     /* check if we have the header */
1633     if ((RECORD_LAYER_get_rstate(&s->rlayer) != SSL_ST_READ_BODY) ||
1634         (RECORD_LAYER_get_packet_length(&s->rlayer) < DTLS1_RT_HEADER_LENGTH)) {
1635         rret = ssl3_read_n(s, DTLS1_RT_HEADER_LENGTH,
1636                            SSL3_BUFFER_get_len(&s->rlayer.rbuf), 0, 1, &n);
1637         /* read timeout is handled by dtls1_read_bytes */
1638         if (rret <= 0)
1639             return rret;         /* error or non-blocking */
1640
1641         /* this packet contained a partial record, dump it */
1642         if (RECORD_LAYER_get_packet_length(&s->rlayer) !=
1643             DTLS1_RT_HEADER_LENGTH) {
1644             RECORD_LAYER_reset_packet_length(&s->rlayer);
1645             goto again;
1646         }
1647
1648         RECORD_LAYER_set_rstate(&s->rlayer, SSL_ST_READ_BODY);
1649
1650         p = RECORD_LAYER_get_packet(&s->rlayer);
1651
1652         if (s->msg_callback)
1653             s->msg_callback(0, 0, SSL3_RT_HEADER, p, DTLS1_RT_HEADER_LENGTH,
1654                             s, s->msg_callback_arg);
1655
1656         /* Pull apart the header into the DTLS1_RECORD */
1657         rr->type = *(p++);
1658         ssl_major = *(p++);
1659         ssl_minor = *(p++);
1660         version = (ssl_major << 8) | ssl_minor;
1661
1662         /* sequence number is 64 bits, with top 2 bytes = epoch */
1663         n2s(p, rr->epoch);
1664
1665         memcpy(&(RECORD_LAYER_get_read_sequence(&s->rlayer)[2]), p, 6);
1666         p += 6;
1667
1668         n2s(p, rr->length);
1669
1670         /* Lets check version */
1671         if (!s->first_packet) {
1672             if (version != s->version) {
1673                 /* unexpected version, silently discard */
1674                 rr->length = 0;
1675                 RECORD_LAYER_reset_packet_length(&s->rlayer);
1676                 goto again;
1677             }
1678         }
1679
1680         if ((version & 0xff00) != (s->version & 0xff00)) {
1681             /* wrong version, silently discard record */
1682             rr->length = 0;
1683             RECORD_LAYER_reset_packet_length(&s->rlayer);
1684             goto again;
1685         }
1686
1687         if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
1688             /* record too long, silently discard it */
1689             rr->length = 0;
1690             RECORD_LAYER_reset_packet_length(&s->rlayer);
1691             goto again;
1692         }
1693
1694         /* now s->rlayer.rstate == SSL_ST_READ_BODY */
1695     }
1696
1697     /* s->rlayer.rstate == SSL_ST_READ_BODY, get and decode the data */
1698
1699     if (rr->length >
1700         RECORD_LAYER_get_packet_length(&s->rlayer) - DTLS1_RT_HEADER_LENGTH) {
1701         /* now s->packet_length == DTLS1_RT_HEADER_LENGTH */
1702         more = rr->length;
1703         rret = ssl3_read_n(s, more, more, 1, 1, &n);
1704         /* this packet contained a partial record, dump it */
1705         if (rret <= 0 || n != more) {
1706             rr->length = 0;
1707             RECORD_LAYER_reset_packet_length(&s->rlayer);
1708             goto again;
1709         }
1710
1711         /*
1712          * now n == rr->length, and s->packet_length ==
1713          * DTLS1_RT_HEADER_LENGTH + rr->length
1714          */
1715     }
1716     /* set state for later operations */
1717     RECORD_LAYER_set_rstate(&s->rlayer, SSL_ST_READ_HEADER);
1718
1719     /* match epochs.  NULL means the packet is dropped on the floor */
1720     bitmap = dtls1_get_bitmap(s, rr, &is_next_epoch);
1721     if (bitmap == NULL) {
1722         rr->length = 0;
1723         RECORD_LAYER_reset_packet_length(&s->rlayer); /* dump this record */
1724         goto again;             /* get another record */
1725     }
1726 #ifndef OPENSSL_NO_SCTP
1727     /* Only do replay check if no SCTP bio */
1728     if (!BIO_dgram_is_sctp(SSL_get_rbio(s))) {
1729 #endif
1730         /* Check whether this is a repeat, or aged record. */
1731         /*
1732          * TODO: Does it make sense to have replay protection in epoch 0 where
1733          * we have no integrity negotiated yet?
1734          */
1735         if (!dtls1_record_replay_check(s, bitmap)) {
1736             rr->length = 0;
1737             RECORD_LAYER_reset_packet_length(&s->rlayer); /* dump this record */
1738             goto again;         /* get another record */
1739         }
1740 #ifndef OPENSSL_NO_SCTP
1741     }
1742 #endif
1743
1744     /* just read a 0 length packet */
1745     if (rr->length == 0)
1746         goto again;
1747
1748     /*
1749      * If this record is from the next epoch (either HM or ALERT), and a
1750      * handshake is currently in progress, buffer it since it cannot be
1751      * processed at this time.
1752      */
1753     if (is_next_epoch) {
1754         if ((SSL_in_init(s) || ossl_statem_get_in_handshake(s))) {
1755             if (dtls1_buffer_record
1756                 (s, &(DTLS_RECORD_LAYER_get_unprocessed_rcds(&s->rlayer)),
1757                  rr->seq_num) < 0)
1758                 return -1;
1759         }
1760         rr->length = 0;
1761         RECORD_LAYER_reset_packet_length(&s->rlayer);
1762         goto again;
1763     }
1764
1765     if (!dtls1_process_record(s, bitmap)) {
1766         rr->length = 0;
1767         RECORD_LAYER_reset_packet_length(&s->rlayer); /* dump this record */
1768         goto again;             /* get another record */
1769     }
1770
1771     return (1);
1772
1773 }