Coverage Report

Created: 2022-08-24 06:31

/src/libressl/ssl/ssl_pkt.c
Line
Count
Source (jump to first uncovered line)
1
/* $OpenBSD: ssl_pkt.c,v 1.58 2022/03/26 15:05:53 jsing Exp $ */
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-2002 The OpenSSL Project.  All rights reserved.
60
 *
61
 * Redistribution and use in source and binary forms, with or without
62
 * modification, are permitted provided that the following conditions
63
 * are met:
64
 *
65
 * 1. Redistributions of source code must retain the above copyright
66
 *    notice, this list of conditions and the following disclaimer.
67
 *
68
 * 2. Redistributions in binary form must reproduce the above copyright
69
 *    notice, this list of conditions and the following disclaimer in
70
 *    the documentation and/or other materials provided with the
71
 *    distribution.
72
 *
73
 * 3. All advertising materials mentioning features or use of this
74
 *    software must display the following acknowledgment:
75
 *    "This product includes software developed by the OpenSSL Project
76
 *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
77
 *
78
 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
79
 *    endorse or promote products derived from this software without
80
 *    prior written permission. For written permission, please contact
81
 *    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 <errno.h>
113
#include <stdio.h>
114
115
#include <openssl/buffer.h>
116
#include <openssl/evp.h>
117
118
#include "bytestring.h"
119
#include "dtls_locl.h"
120
#include "ssl_locl.h"
121
122
static int do_ssl3_write(SSL *s, int type, const unsigned char *buf,
123
    unsigned int len);
124
static int ssl3_get_record(SSL *s);
125
126
/*
127
 * Force a WANT_READ return for certain error conditions where
128
 * we don't want to spin internally.
129
 */
130
void
131
ssl_force_want_read(SSL *s)
132
0
{
133
0
  BIO *bio;
134
135
0
  bio = SSL_get_rbio(s);
136
0
  BIO_clear_retry_flags(bio);
137
0
  BIO_set_retry_read(bio);
138
139
0
  s->internal->rwstate = SSL_READING;
140
0
}
141
142
/*
143
 * If extend == 0, obtain new n-byte packet; if extend == 1, increase
144
 * packet by another n bytes.
145
 * The packet will be in the sub-array of s->s3->rbuf.buf specified
146
 * by s->internal->packet and s->internal->packet_length.
147
 * (If s->internal->read_ahead is set, 'max' bytes may be stored in rbuf
148
 * [plus s->internal->packet_length bytes if extend == 1].)
149
 */
150
static int
151
ssl3_read_n(SSL *s, int n, int max, int extend)
152
0
{
153
0
  SSL3_BUFFER_INTERNAL *rb = &(s->s3->rbuf);
154
0
  int i, len, left;
155
0
  size_t align;
156
0
  unsigned char *pkt;
157
158
0
  if (n <= 0)
159
0
    return n;
160
161
0
  if (rb->buf == NULL)
162
0
    if (!ssl3_setup_read_buffer(s))
163
0
      return -1;
164
165
0
  left = rb->left;
166
0
  align = (size_t)rb->buf + SSL3_RT_HEADER_LENGTH;
167
0
  align = (-align) & (SSL3_ALIGN_PAYLOAD - 1);
168
169
0
  if (!extend) {
170
    /* start with empty packet ... */
171
0
    if (left == 0)
172
0
      rb->offset = align;
173
0
    else if (align != 0 && left >= SSL3_RT_HEADER_LENGTH) {
174
      /* check if next packet length is large
175
       * enough to justify payload alignment... */
176
0
      pkt = rb->buf + rb->offset;
177
0
      if (pkt[0] == SSL3_RT_APPLICATION_DATA &&
178
0
          (pkt[3]<<8|pkt[4]) >= 128) {
179
        /* Note that even if packet is corrupted
180
         * and its length field is insane, we can
181
         * only be led to wrong decision about
182
         * whether memmove will occur or not.
183
         * Header values has no effect on memmove
184
         * arguments and therefore no buffer
185
         * overrun can be triggered. */
186
0
        memmove(rb->buf + align, pkt, left);
187
0
        rb->offset = align;
188
0
      }
189
0
    }
190
0
    s->internal->packet = rb->buf + rb->offset;
191
0
    s->internal->packet_length = 0;
192
    /* ... now we can act as if 'extend' was set */
193
0
  }
194
195
  /* For DTLS/UDP reads should not span multiple packets
196
   * because the read operation returns the whole packet
197
   * at once (as long as it fits into the buffer). */
198
0
  if (SSL_is_dtls(s)) {
199
0
    if (left > 0 && n > left)
200
0
      n = left;
201
0
  }
202
203
  /* if there is enough in the buffer from a previous read, take some */
204
0
  if (left >= n) {
205
0
    s->internal->packet_length += n;
206
0
    rb->left = left - n;
207
0
    rb->offset += n;
208
0
    return (n);
209
0
  }
210
211
  /* else we need to read more data */
212
213
0
  len = s->internal->packet_length;
214
0
  pkt = rb->buf + align;
215
  /* Move any available bytes to front of buffer:
216
   * 'len' bytes already pointed to by 'packet',
217
   * 'left' extra ones at the end */
218
0
  if (s->internal->packet != pkt)  {
219
    /* len > 0 */
220
0
    memmove(pkt, s->internal->packet, len + left);
221
0
    s->internal->packet = pkt;
222
0
    rb->offset = len + align;
223
0
  }
224
225
0
  if (n > (int)(rb->len - rb->offset)) {
226
    /* does not happen */
227
0
    SSLerror(s, ERR_R_INTERNAL_ERROR);
228
0
    return -1;
229
0
  }
230
231
0
  if (s->internal->read_ahead || SSL_is_dtls(s)) {
232
0
    if (max < n)
233
0
      max = n;
234
0
    if (max > (int)(rb->len - rb->offset))
235
0
      max = rb->len - rb->offset;
236
0
  } else {
237
    /* ignore max parameter */
238
0
    max = n;
239
0
  }
240
241
0
  while (left < n) {
242
    /* Now we have len+left bytes at the front of s->s3->rbuf.buf
243
     * and need to read in more until we have len+n (up to
244
     * len+max if possible) */
245
246
0
    errno = 0;
247
0
    if (s->rbio != NULL) {
248
0
      s->internal->rwstate = SSL_READING;
249
0
      i = BIO_read(s->rbio, pkt + len + left, max - left);
250
0
    } else {
251
0
      SSLerror(s, SSL_R_READ_BIO_NOT_SET);
252
0
      i = -1;
253
0
    }
254
255
0
    if (i <= 0) {
256
0
      rb->left = left;
257
0
      if (s->internal->mode & SSL_MODE_RELEASE_BUFFERS &&
258
0
          !SSL_is_dtls(s)) {
259
0
        if (len + left == 0)
260
0
          ssl3_release_read_buffer(s);
261
0
      }
262
0
      return (i);
263
0
    }
264
0
    left += i;
265
266
    /*
267
     * reads should *never* span multiple packets for DTLS because
268
     * the underlying transport protocol is message oriented as
269
     * opposed to byte oriented as in the TLS case.
270
     */
271
0
    if (SSL_is_dtls(s)) {
272
0
      if (n > left)
273
0
        n = left; /* makes the while condition false */
274
0
    }
275
0
  }
276
277
  /* done reading, now the book-keeping */
278
0
  rb->offset += n;
279
0
  rb->left = left - n;
280
0
  s->internal->packet_length += n;
281
0
  s->internal->rwstate = SSL_NOTHING;
282
283
0
  return (n);
284
0
}
285
286
int
287
ssl3_packet_read(SSL *s, int plen)
288
0
{
289
0
  int n;
290
291
0
  n = ssl3_read_n(s, plen, s->s3->rbuf.len, 0);
292
0
  if (n <= 0)
293
0
    return n;
294
0
  if (s->internal->packet_length < plen)
295
0
    return s->internal->packet_length;
296
297
0
  return plen;
298
0
}
299
300
int
301
ssl3_packet_extend(SSL *s, int plen)
302
0
{
303
0
  int rlen, n;
304
305
0
  if (s->internal->packet_length >= plen)
306
0
    return plen;
307
0
  rlen = plen - s->internal->packet_length;
308
309
0
  n = ssl3_read_n(s, rlen, rlen, 1);
310
0
  if (n <= 0)
311
0
    return n;
312
0
  if (s->internal->packet_length < plen)
313
0
    return s->internal->packet_length;
314
315
0
  return plen;
316
0
}
317
318
/* Call this to get a new input record.
319
 * It will return <= 0 if more data is needed, normally due to an error
320
 * or non-blocking IO.
321
 * When it finishes, one packet has been decoded and can be found in
322
 * ssl->s3->internal->rrec.type    - is the type of record
323
 * ssl->s3->internal->rrec.data,   - data
324
 * ssl->s3->internal->rrec.length, - number of bytes
325
 */
326
/* used only by ssl3_read_bytes */
327
static int
328
ssl3_get_record(SSL *s)
329
0
{
330
0
  SSL3_BUFFER_INTERNAL *rb = &(s->s3->rbuf);
331
0
  SSL3_RECORD_INTERNAL *rr = &(s->s3->rrec);
332
0
  uint8_t alert_desc;
333
0
  uint8_t *out;
334
0
  size_t out_len;
335
0
  int al, n;
336
0
  int ret = -1;
337
338
0
 again:
339
  /* check if we have the header */
340
0
  if ((s->internal->rstate != SSL_ST_READ_BODY) ||
341
0
      (s->internal->packet_length < SSL3_RT_HEADER_LENGTH)) {
342
0
    CBS header;
343
0
    uint16_t len, ssl_version;
344
0
    uint8_t type;
345
346
0
    n = ssl3_packet_read(s, SSL3_RT_HEADER_LENGTH);
347
0
    if (n <= 0)
348
0
      return (n);
349
350
0
    s->internal->mac_packet = 1;
351
0
    s->internal->rstate = SSL_ST_READ_BODY;
352
353
0
    if (s->server && s->internal->first_packet) {
354
0
      if ((ret = ssl_server_legacy_first_packet(s)) != 1)
355
0
        return (ret);
356
0
      ret = -1;
357
0
    }
358
359
0
    CBS_init(&header, s->internal->packet, SSL3_RT_HEADER_LENGTH);
360
361
    /* Pull apart the header into the SSL3_RECORD_INTERNAL */
362
0
    if (!CBS_get_u8(&header, &type) ||
363
0
        !CBS_get_u16(&header, &ssl_version) ||
364
0
        !CBS_get_u16(&header, &len)) {
365
0
      SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
366
0
      goto err;
367
0
    }
368
369
0
    rr->type = type;
370
0
    rr->length = len;
371
372
    /* Lets check version */
373
0
    if (!s->internal->first_packet && ssl_version != s->version) {
374
0
      if ((s->version & 0xFF00) == (ssl_version & 0xFF00) &&
375
0
          !tls12_record_layer_write_protected(s->internal->rl)) {
376
        /* Send back error using their minor version number :-) */
377
0
        s->version = ssl_version;
378
0
      }
379
0
      SSLerror(s, SSL_R_WRONG_VERSION_NUMBER);
380
0
      al = SSL_AD_PROTOCOL_VERSION;
381
0
      goto fatal_err;
382
0
    }
383
384
0
    if ((ssl_version >> 8) != SSL3_VERSION_MAJOR) {
385
0
      SSLerror(s, SSL_R_WRONG_VERSION_NUMBER);
386
0
      goto err;
387
0
    }
388
389
0
    if (rr->length > rb->len - SSL3_RT_HEADER_LENGTH) {
390
0
      al = SSL_AD_RECORD_OVERFLOW;
391
0
      SSLerror(s, SSL_R_PACKET_LENGTH_TOO_LONG);
392
0
      goto fatal_err;
393
0
    }
394
0
  }
395
396
0
  n = ssl3_packet_extend(s, SSL3_RT_HEADER_LENGTH + rr->length);
397
0
  if (n <= 0)
398
0
    return (n);
399
0
  if (n != SSL3_RT_HEADER_LENGTH + rr->length)
400
0
    return (n);
401
402
0
  s->internal->rstate = SSL_ST_READ_HEADER; /* set state for later operations */
403
404
  /*
405
   * A full record has now been read from the wire, which now needs
406
   * to be processed.
407
   */
408
0
  tls12_record_layer_set_version(s->internal->rl, s->version);
409
410
0
  if (!tls12_record_layer_open_record(s->internal->rl, s->internal->packet,
411
0
      s->internal->packet_length, &out, &out_len)) {
412
0
    tls12_record_layer_alert(s->internal->rl, &alert_desc);
413
414
0
    if (alert_desc == 0)
415
0
      goto err;
416
417
0
    if (alert_desc == SSL_AD_RECORD_OVERFLOW)
418
0
      SSLerror(s, SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
419
0
    else if (alert_desc == SSL_AD_BAD_RECORD_MAC)
420
0
      SSLerror(s, SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
421
422
0
    al = alert_desc;
423
0
    goto fatal_err;
424
0
  }
425
426
0
  rr->data = out;
427
0
  rr->length = out_len;
428
0
  rr->off = 0;
429
430
  /* we have pulled in a full packet so zero things */
431
0
  s->internal->packet_length = 0;
432
433
0
  if (rr->length == 0) {
434
    /*
435
     * Zero-length fragments are only permitted for application
436
     * data, as per RFC 5246 section 6.2.1.
437
     */
438
0
    if (rr->type != SSL3_RT_APPLICATION_DATA) {
439
0
      SSLerror(s, SSL_R_BAD_LENGTH);
440
0
      al = SSL_AD_UNEXPECTED_MESSAGE;
441
0
      goto fatal_err;
442
0
    }
443
444
    /*
445
     * CBC countermeasures for known IV weaknesses can legitimately
446
     * insert a single empty record, so we allow ourselves to read
447
     * once past a single empty record without forcing want_read.
448
     */
449
0
    if (s->internal->empty_record_count++ > SSL_MAX_EMPTY_RECORDS) {
450
0
      SSLerror(s, SSL_R_PEER_BEHAVING_BADLY);
451
0
      return -1;
452
0
    }
453
0
    if (s->internal->empty_record_count > 1) {
454
0
      ssl_force_want_read(s);
455
0
      return -1;
456
0
    }
457
0
    goto again;
458
0
  }
459
460
0
  s->internal->empty_record_count = 0;
461
462
0
  return (1);
463
464
0
 fatal_err:
465
0
  ssl3_send_alert(s, SSL3_AL_FATAL, al);
466
0
 err:
467
0
  return (ret);
468
0
}
469
470
/* Call this to write data in records of type 'type'
471
 * It will return <= 0 if not all data has been sent or non-blocking IO.
472
 */
473
int
474
ssl3_write_bytes(SSL *s, int type, const void *buf_, int len)
475
0
{
476
0
  const unsigned char *buf = buf_;
477
0
  unsigned int tot, n, nw;
478
0
  int i;
479
480
0
  if (len < 0) {
481
0
    SSLerror(s, ERR_R_INTERNAL_ERROR);
482
0
    return -1;
483
0
  }
484
485
0
  s->internal->rwstate = SSL_NOTHING;
486
0
  tot = s->s3->wnum;
487
0
  s->s3->wnum = 0;
488
489
0
  if (SSL_in_init(s) && !s->internal->in_handshake) {
490
0
    i = s->internal->handshake_func(s);
491
0
    if (i < 0)
492
0
      return (i);
493
0
    if (i == 0) {
494
0
      SSLerror(s, SSL_R_SSL_HANDSHAKE_FAILURE);
495
0
      return -1;
496
0
    }
497
0
  }
498
499
0
  if (len < tot)
500
0
    len = tot;
501
0
  n = (len - tot);
502
0
  for (;;) {
503
0
    if (n > s->max_send_fragment)
504
0
      nw = s->max_send_fragment;
505
0
    else
506
0
      nw = n;
507
508
0
    i = do_ssl3_write(s, type, &(buf[tot]), nw);
509
0
    if (i <= 0) {
510
0
      s->s3->wnum = tot;
511
0
      return i;
512
0
    }
513
514
0
    if ((i == (int)n) || (type == SSL3_RT_APPLICATION_DATA &&
515
0
        (s->internal->mode & SSL_MODE_ENABLE_PARTIAL_WRITE))) {
516
      /*
517
       * Next chunk of data should get another prepended
518
       * empty fragment in ciphersuites with known-IV
519
       * weakness.
520
       */
521
0
      s->s3->empty_fragment_done = 0;
522
523
0
      return tot + i;
524
0
    }
525
526
0
    n -= i;
527
0
    tot += i;
528
0
  }
529
0
}
530
531
static int
532
do_ssl3_write(SSL *s, int type, const unsigned char *buf, unsigned int len)
533
0
{
534
0
  SSL3_BUFFER_INTERNAL *wb = &(s->s3->wbuf);
535
0
  SSL_SESSION *sess = s->session;
536
0
  int need_empty_fragment = 0;
537
0
  size_t align, out_len;
538
0
  uint16_t version;
539
0
  CBB cbb;
540
0
  int ret;
541
542
0
  memset(&cbb, 0, sizeof(cbb));
543
544
0
  if (wb->buf == NULL)
545
0
    if (!ssl3_setup_write_buffer(s))
546
0
      return -1;
547
548
  /*
549
   * First check if there is a SSL3_BUFFER_INTERNAL still being written
550
   * out.  This will happen with non blocking IO.
551
   */
552
0
  if (wb->left != 0)
553
0
    return (ssl3_write_pending(s, type, buf, len));
554
555
  /* If we have an alert to send, let's send it. */
556
0
  if (s->s3->alert_dispatch) {
557
0
    if ((ret = ssl3_dispatch_alert(s)) <= 0)
558
0
      return (ret);
559
    /* If it went, fall through and send more stuff. */
560
561
    /* We may have released our buffer, if so get it again. */
562
0
    if (wb->buf == NULL)
563
0
      if (!ssl3_setup_write_buffer(s))
564
0
        return -1;
565
0
  }
566
567
0
  if (len == 0)
568
0
    return 0;
569
570
  /*
571
   * Some servers hang if initial client hello is larger than 256
572
   * bytes and record version number > TLS 1.0.
573
   */
574
0
  version = s->version;
575
0
  if (s->s3->hs.state == SSL3_ST_CW_CLNT_HELLO_B &&
576
0
      !s->internal->renegotiate &&
577
0
      s->s3->hs.our_max_tls_version > TLS1_VERSION)
578
0
    version = TLS1_VERSION;
579
580
  /*
581
   * Countermeasure against known-IV weakness in CBC ciphersuites
582
   * (see http://www.openssl.org/~bodo/tls-cbc.txt). Note that this
583
   * is unnecessary for AEAD.
584
   */
585
0
  if (sess != NULL && tls12_record_layer_write_protected(s->internal->rl)) {
586
0
    if (s->s3->need_empty_fragments &&
587
0
        !s->s3->empty_fragment_done &&
588
0
        type == SSL3_RT_APPLICATION_DATA)
589
0
      need_empty_fragment = 1;
590
0
  }
591
592
  /*
593
   * An extra fragment would be a couple of cipher blocks, which would
594
   * be a multiple of SSL3_ALIGN_PAYLOAD, so if we want to align the real
595
   * payload, then we can just simply pretend we have two headers.
596
   */
597
0
  align = (size_t)wb->buf + SSL3_RT_HEADER_LENGTH;
598
0
  if (need_empty_fragment)
599
0
    align += SSL3_RT_HEADER_LENGTH;
600
0
  align = (-align) & (SSL3_ALIGN_PAYLOAD - 1);
601
0
  wb->offset = align;
602
603
0
  if (!CBB_init_fixed(&cbb, wb->buf + align, wb->len - align))
604
0
    goto err;
605
606
0
  tls12_record_layer_set_version(s->internal->rl, version);
607
608
0
  if (need_empty_fragment) {
609
0
    if (!tls12_record_layer_seal_record(s->internal->rl, type,
610
0
        buf, 0, &cbb))
611
0
      goto err;
612
0
    s->s3->empty_fragment_done = 1;
613
0
  }
614
615
0
  if (!tls12_record_layer_seal_record(s->internal->rl, type, buf, len, &cbb))
616
0
    goto err;
617
618
0
  if (!CBB_finish(&cbb, NULL, &out_len))
619
0
    goto err;
620
621
0
  wb->left = out_len;
622
623
  /*
624
   * Memorize arguments so that ssl3_write_pending can detect
625
   * bad write retries later.
626
   */
627
0
  s->s3->wpend_tot = len;
628
0
  s->s3->wpend_buf = buf;
629
0
  s->s3->wpend_type = type;
630
0
  s->s3->wpend_ret = len;
631
632
  /* We now just need to write the buffer. */
633
0
  return ssl3_write_pending(s, type, buf, len);
634
635
0
 err:
636
0
  CBB_cleanup(&cbb);
637
638
0
  return -1;
639
0
}
640
641
/* if s->s3->wbuf.left != 0, we need to call this */
642
int
643
ssl3_write_pending(SSL *s, int type, const unsigned char *buf, unsigned int len)
644
0
{
645
0
  int i;
646
0
  SSL3_BUFFER_INTERNAL *wb = &(s->s3->wbuf);
647
648
  /* XXXX */
649
0
  if ((s->s3->wpend_tot > (int)len) || ((s->s3->wpend_buf != buf) &&
650
0
      !(s->internal->mode & SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER)) ||
651
0
      (s->s3->wpend_type != type)) {
652
0
    SSLerror(s, SSL_R_BAD_WRITE_RETRY);
653
0
    return (-1);
654
0
  }
655
656
0
  for (;;) {
657
0
    errno = 0;
658
0
    if (s->wbio != NULL) {
659
0
      s->internal->rwstate = SSL_WRITING;
660
0
      i = BIO_write(s->wbio, (char *)&(wb->buf[wb->offset]),
661
0
          (unsigned int)wb->left);
662
0
    } else {
663
0
      SSLerror(s, SSL_R_BIO_NOT_SET);
664
0
      i = -1;
665
0
    }
666
0
    if (i == wb->left) {
667
0
      wb->left = 0;
668
0
      wb->offset += i;
669
0
      if (s->internal->mode & SSL_MODE_RELEASE_BUFFERS &&
670
0
          !SSL_is_dtls(s))
671
0
        ssl3_release_write_buffer(s);
672
0
      s->internal->rwstate = SSL_NOTHING;
673
0
      return (s->s3->wpend_ret);
674
0
    } else if (i <= 0) {
675
      /*
676
       * For DTLS, just drop it. That's kind of the
677
       * whole point in using a datagram service.
678
       */
679
0
      if (SSL_is_dtls(s))
680
0
        wb->left = 0;
681
0
      return (i);
682
0
    }
683
0
    wb->offset += i;
684
0
    wb->left -= i;
685
0
  }
686
0
}
687
688
int
689
ssl3_read_alert(SSL *s)
690
0
{
691
0
  SSL3_RECORD_INTERNAL *rr = &s->s3->rrec;
692
0
  uint8_t alert_level, alert_descr;
693
694
  /*
695
   * TLSv1.2 permits an alert to be fragmented across multiple records or
696
   * for multiple alerts to be be coalesced into a single alert record.
697
   * In the case of DTLS, there is no way to reassemble an alert
698
   * fragmented across multiple records, hence a full alert must be
699
   * available in the record.
700
   */
701
0
  while (rr->length > 0 &&
702
0
      s->s3->alert_fragment_len < sizeof(s->s3->alert_fragment)) {
703
0
    s->s3->alert_fragment[s->s3->alert_fragment_len++] =
704
0
        rr->data[rr->off++];
705
0
    rr->length--;
706
0
  }
707
0
  if (s->s3->alert_fragment_len < sizeof(s->s3->alert_fragment)) {
708
0
    if (SSL_is_dtls(s)) {
709
0
      SSLerror(s, SSL_R_BAD_LENGTH);
710
0
      ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
711
0
      return -1;
712
0
    }
713
0
    return 1;
714
0
  }
715
716
0
  ssl_msg_callback(s, 0, SSL3_RT_ALERT, s->s3->alert_fragment, 2);
717
718
0
  alert_level = s->s3->alert_fragment[0];
719
0
  alert_descr = s->s3->alert_fragment[1];
720
0
  s->s3->alert_fragment_len = 0;
721
722
0
  ssl_info_callback(s, SSL_CB_READ_ALERT,
723
0
      (alert_level << 8) | alert_descr);
724
725
0
  if (alert_level == SSL3_AL_WARNING) {
726
0
    s->s3->warn_alert = alert_descr;
727
0
    if (alert_descr == SSL_AD_CLOSE_NOTIFY) {
728
0
      s->internal->shutdown |= SSL_RECEIVED_SHUTDOWN;
729
0
      return 0;
730
0
    }
731
    /* We requested renegotiation and the peer rejected it. */
732
0
    if (alert_descr == SSL_AD_NO_RENEGOTIATION) {
733
0
      SSLerror(s, SSL_R_NO_RENEGOTIATION);
734
0
      ssl3_send_alert(s, SSL3_AL_FATAL,
735
0
          SSL_AD_HANDSHAKE_FAILURE);
736
0
      return -1;
737
0
    }
738
0
  } else if (alert_level == SSL3_AL_FATAL) {
739
0
    s->internal->rwstate = SSL_NOTHING;
740
0
    s->s3->fatal_alert = alert_descr;
741
0
    SSLerror(s, SSL_AD_REASON_OFFSET + alert_descr);
742
0
    ERR_asprintf_error_data("SSL alert number %d", alert_descr);
743
0
    s->internal->shutdown |= SSL_RECEIVED_SHUTDOWN;
744
0
    SSL_CTX_remove_session(s->ctx, s->session);
745
0
    return 0;
746
0
  } else {
747
0
    SSLerror(s, SSL_R_UNKNOWN_ALERT_TYPE);
748
0
    ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
749
0
    return -1;
750
0
  }
751
752
0
  return 1;
753
0
}
754
755
int
756
ssl3_read_change_cipher_spec(SSL *s)
757
0
{
758
0
  SSL3_RECORD_INTERNAL *rr = &s->s3->rrec;
759
760
  /*
761
   * 'Change Cipher Spec' is just a single byte, so we know exactly what
762
   * the record payload has to look like.
763
   */
764
0
  if (rr->length != 1 || rr->off != 0) {
765
0
    SSLerror(s, SSL_R_BAD_CHANGE_CIPHER_SPEC);
766
0
    ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
767
0
    return -1;
768
0
  }
769
0
  if (rr->data[0] != SSL3_MT_CCS) {
770
0
    SSLerror(s, SSL_R_BAD_CHANGE_CIPHER_SPEC);
771
0
    ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
772
0
    return -1;
773
0
  }
774
775
  /* XDTLS: check that epoch is consistent */
776
777
0
  ssl_msg_callback(s, 0, SSL3_RT_CHANGE_CIPHER_SPEC, rr->data, 1);
778
779
  /* Check that we have a cipher to change to. */
780
0
  if (s->s3->hs.cipher == NULL) {
781
0
    SSLerror(s, SSL_R_CCS_RECEIVED_EARLY);
782
0
    ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
783
0
    return -1;
784
0
  }
785
786
  /* Check that we should be receiving a Change Cipher Spec. */
787
0
  if (SSL_is_dtls(s)) {
788
0
    if (!s->d1->change_cipher_spec_ok) {
789
      /*
790
       * We can't process a CCS now, because previous
791
       * handshake messages are still missing, so just
792
       * drop it.
793
       */
794
0
      rr->length = 0;
795
0
      return 1;
796
0
    }
797
0
    s->d1->change_cipher_spec_ok = 0;
798
0
  } else {
799
0
    if ((s->s3->flags & SSL3_FLAGS_CCS_OK) == 0) {
800
0
      SSLerror(s, SSL_R_CCS_RECEIVED_EARLY);
801
0
      ssl3_send_alert(s, SSL3_AL_FATAL,
802
0
          SSL_AD_UNEXPECTED_MESSAGE);
803
0
      return -1;
804
0
    }
805
0
    s->s3->flags &= ~SSL3_FLAGS_CCS_OK;
806
0
  }
807
808
0
  rr->length = 0;
809
810
0
  s->s3->change_cipher_spec = 1;
811
0
  if (!ssl3_do_change_cipher_spec(s))
812
0
    return -1;
813
814
0
  return 1;
815
0
}
816
817
static int
818
ssl3_read_handshake_unexpected(SSL *s)
819
0
{
820
0
  SSL3_RECORD_INTERNAL *rr = &s->s3->rrec;
821
0
  uint32_t hs_msg_length;
822
0
  uint8_t hs_msg_type;
823
0
  CBS cbs;
824
0
  int ret;
825
826
  /*
827
   * We need four bytes of handshake data so we have a handshake message
828
   * header - this may be in the same record or fragmented across multiple
829
   * records.
830
   */
831
0
  while (rr->length > 0 &&
832
0
      s->s3->handshake_fragment_len < sizeof(s->s3->handshake_fragment)) {
833
0
    s->s3->handshake_fragment[s->s3->handshake_fragment_len++] =
834
0
        rr->data[rr->off++];
835
0
    rr->length--;
836
0
  }
837
838
0
  if (s->s3->handshake_fragment_len < sizeof(s->s3->handshake_fragment))
839
0
    return 1;
840
841
0
  if (s->internal->in_handshake) {
842
0
    SSLerror(s, ERR_R_INTERNAL_ERROR);
843
0
    return -1;
844
0
  }
845
846
  /*
847
   * This code currently deals with HelloRequest and ClientHello messages -
848
   * anything else is pushed to the handshake_func. Almost all of this
849
   * belongs in the client/server handshake code.
850
   */
851
852
  /* Parse handshake message header. */
853
0
  CBS_init(&cbs, s->s3->handshake_fragment, s->s3->handshake_fragment_len);
854
0
  if (!CBS_get_u8(&cbs, &hs_msg_type))
855
0
    return -1;
856
0
  if (!CBS_get_u24(&cbs, &hs_msg_length))
857
0
    return -1;
858
859
0
  if (hs_msg_type == SSL3_MT_HELLO_REQUEST) {
860
    /*
861
     * Incoming HelloRequest messages should only be received by a
862
     * client. A server may send these at any time - a client should
863
     * ignore the message if received in the middle of a handshake.
864
     * See RFC 5246 sections 7.4 and 7.4.1.1.
865
     */
866
0
    if (s->server) {
867
0
      SSLerror(s, SSL_R_UNEXPECTED_MESSAGE);
868
0
      ssl3_send_alert(s, SSL3_AL_FATAL,
869
0
           SSL_AD_UNEXPECTED_MESSAGE);
870
0
      return -1;
871
0
    }
872
873
0
    if (hs_msg_length != 0) {
874
0
      SSLerror(s, SSL_R_BAD_HELLO_REQUEST);
875
0
      ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
876
0
      return -1;
877
0
    }
878
879
0
    ssl_msg_callback(s, 0, SSL3_RT_HANDSHAKE,
880
0
        s->s3->handshake_fragment, s->s3->handshake_fragment_len);
881
882
0
    s->s3->handshake_fragment_len = 0;
883
884
    /*
885
     * It should be impossible to hit this, but keep the safety
886
     * harness for now...
887
     */
888
0
    if (s->session == NULL || s->session->cipher == NULL)
889
0
      return 1;
890
891
    /*
892
     * Ignore this message if we're currently handshaking,
893
     * renegotiation is already pending or renegotiation is disabled
894
     * via flags.
895
     */
896
0
    if (!SSL_is_init_finished(s) || s->s3->renegotiate ||
897
0
        (s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS) != 0)
898
0
      return 1;
899
900
0
    if (!ssl3_renegotiate(s))
901
0
      return 1;
902
0
    if (!ssl3_renegotiate_check(s))
903
0
      return 1;
904
905
0
  } else if (hs_msg_type == SSL3_MT_CLIENT_HELLO) {
906
    /*
907
     * Incoming ClientHello messages should only be received by a
908
     * server. A client may send these in response to server
909
     * initiated renegotiation (HelloRequest) or in order to
910
     * initiate renegotiation by the client. See RFC 5246 section
911
     * 7.4.1.2.
912
     */
913
0
    if (!s->server) {
914
0
      SSLerror(s, SSL_R_UNEXPECTED_MESSAGE);
915
0
      ssl3_send_alert(s, SSL3_AL_FATAL,
916
0
           SSL_AD_UNEXPECTED_MESSAGE);
917
0
      return -1;
918
0
    }
919
920
    /*
921
     * A client should not be sending a ClientHello unless we're not
922
     * currently handshaking.
923
     */
924
0
    if (!SSL_is_init_finished(s)) {
925
0
      SSLerror(s, SSL_R_UNEXPECTED_MESSAGE);
926
0
      ssl3_send_alert(s, SSL3_AL_FATAL,
927
0
          SSL_AD_UNEXPECTED_MESSAGE);
928
0
      return -1;
929
0
    }
930
931
0
    if ((s->internal->options & SSL_OP_NO_CLIENT_RENEGOTIATION) != 0) {
932
0
      ssl3_send_alert(s, SSL3_AL_FATAL,
933
0
          SSL_AD_NO_RENEGOTIATION);
934
0
      return -1;
935
0
    }
936
937
0
    if (s->session == NULL || s->session->cipher == NULL) {
938
0
      SSLerror(s, ERR_R_INTERNAL_ERROR);
939
0
      return -1;
940
0
    }
941
942
    /* Client requested renegotiation but it is not permitted. */
943
0
    if (!s->s3->send_connection_binding ||
944
0
        (s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS) != 0) {
945
0
      ssl3_send_alert(s, SSL3_AL_WARNING,
946
0
          SSL_AD_NO_RENEGOTIATION);
947
0
      return 1;
948
0
    }
949
950
0
    s->s3->hs.state = SSL_ST_ACCEPT;
951
0
    s->internal->renegotiate = 1;
952
0
    s->internal->new_session = 1;
953
954
0
  } else {
955
0
    SSLerror(s, SSL_R_UNEXPECTED_MESSAGE);
956
0
    ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
957
0
    return -1;
958
0
  }
959
960
0
  if ((ret = s->internal->handshake_func(s)) < 0)
961
0
    return ret;
962
0
  if (ret == 0) {
963
0
    SSLerror(s, SSL_R_SSL_HANDSHAKE_FAILURE);
964
0
    return -1;
965
0
  }
966
967
0
  if (!(s->internal->mode & SSL_MODE_AUTO_RETRY)) {
968
0
    if (s->s3->rbuf.left == 0) {
969
0
      ssl_force_want_read(s);
970
0
      return -1;
971
0
    }
972
0
  }
973
974
  /*
975
   * We either finished a handshake or ignored the request, now try again
976
   * to obtain the (application) data we were asked for.
977
   */
978
0
  return 1;
979
0
}
980
981
/* Return up to 'len' payload bytes received in 'type' records.
982
 * 'type' is one of the following:
983
 *
984
 *   -  SSL3_RT_HANDSHAKE (when ssl3_get_message calls us)
985
 *   -  SSL3_RT_APPLICATION_DATA (when ssl3_read calls us)
986
 *   -  0 (during a shutdown, no data has to be returned)
987
 *
988
 * If we don't have stored data to work from, read a SSL/TLS record first
989
 * (possibly multiple records if we still don't have anything to return).
990
 *
991
 * This function must handle any surprises the peer may have for us, such as
992
 * Alert records (e.g. close_notify), ChangeCipherSpec records (not really
993
 * a surprise, but handled as if it were), or renegotiation requests.
994
 * Also if record payloads contain fragments too small to process, we store
995
 * them until there is enough for the respective protocol (the record protocol
996
 * may use arbitrary fragmentation and even interleaving):
997
 *     Change cipher spec protocol
998
 *             just 1 byte needed, no need for keeping anything stored
999
 *     Alert protocol
1000
 *             2 bytes needed (AlertLevel, AlertDescription)
1001
 *     Handshake protocol
1002
 *             4 bytes needed (HandshakeType, uint24 length) -- we just have
1003
 *             to detect unexpected Client Hello and Hello Request messages
1004
 *             here, anything else is handled by higher layers
1005
 *     Application data protocol
1006
 *             none of our business
1007
 */
1008
int
1009
ssl3_read_bytes(SSL *s, int type, unsigned char *buf, int len, int peek)
1010
0
{
1011
0
  SSL3_RECORD_INTERNAL *rr;
1012
0
  int rrcount = 0;
1013
0
  unsigned int n;
1014
0
  int ret;
1015
1016
0
  if (s->s3->rbuf.buf == NULL) {
1017
0
    if (!ssl3_setup_read_buffer(s))
1018
0
      return -1;
1019
0
  }
1020
1021
0
  if (len < 0) {
1022
0
    SSLerror(s, ERR_R_INTERNAL_ERROR);
1023
0
    return -1;
1024
0
  }
1025
1026
0
  if (type != 0 && type != SSL3_RT_APPLICATION_DATA &&
1027
0
      type != SSL3_RT_HANDSHAKE) {
1028
0
    SSLerror(s, ERR_R_INTERNAL_ERROR);
1029
0
    return -1;
1030
0
  }
1031
0
  if (peek && type != SSL3_RT_APPLICATION_DATA) {
1032
0
    SSLerror(s, ERR_R_INTERNAL_ERROR);
1033
0
    return -1;
1034
0
  }
1035
1036
0
  if (type == SSL3_RT_HANDSHAKE && s->s3->handshake_fragment_len > 0) {
1037
    /* Partially satisfy request from fragment storage. */
1038
0
    unsigned char *src = s->s3->handshake_fragment;
1039
0
    unsigned char *dst = buf;
1040
0
    unsigned int k;
1041
1042
    /* peek == 0 */
1043
0
    n = 0;
1044
0
    while (len > 0 && s->s3->handshake_fragment_len > 0) {
1045
0
      *dst++ = *src++;
1046
0
      len--;
1047
0
      s->s3->handshake_fragment_len--;
1048
0
      n++;
1049
0
    }
1050
    /* move any remaining fragment bytes: */
1051
0
    for (k = 0; k < s->s3->handshake_fragment_len; k++)
1052
0
      s->s3->handshake_fragment[k] = *src++;
1053
0
    return n;
1054
0
  }
1055
1056
0
  if (SSL_in_init(s) && !s->internal->in_handshake) {
1057
0
    if ((ret = s->internal->handshake_func(s)) < 0)
1058
0
      return ret;
1059
0
    if (ret == 0) {
1060
0
      SSLerror(s, SSL_R_SSL_HANDSHAKE_FAILURE);
1061
0
      return -1;
1062
0
    }
1063
0
  }
1064
1065
0
 start:
1066
  /*
1067
   * Do not process more than three consecutive records, otherwise the
1068
   * peer can cause us to loop indefinitely. Instead, return with an
1069
   * SSL_ERROR_WANT_READ so the caller can choose when to handle further
1070
   * processing. In the future, the total number of non-handshake and
1071
   * non-application data records per connection should probably also be
1072
   * limited...
1073
   */
1074
0
  if (rrcount++ >= 3) {
1075
0
    ssl_force_want_read(s);
1076
0
    return -1;
1077
0
  }
1078
1079
0
  s->internal->rwstate = SSL_NOTHING;
1080
1081
0
  rr = &s->s3->rrec;
1082
1083
0
  if (rr->length == 0 || s->internal->rstate == SSL_ST_READ_BODY) {
1084
0
    if ((ret = ssl3_get_record(s)) <= 0)
1085
0
      return ret;
1086
0
  }
1087
1088
  /* We now have a packet which can be read and processed. */
1089
1090
0
  if (s->s3->change_cipher_spec && rr->type != SSL3_RT_HANDSHAKE) {
1091
0
    SSLerror(s, SSL_R_DATA_BETWEEN_CCS_AND_FINISHED);
1092
0
    ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
1093
0
    return -1;
1094
0
  }
1095
1096
  /*
1097
   * If the other end has shut down, throw anything we read away (even in
1098
   * 'peek' mode).
1099
   */
1100
0
  if (s->internal->shutdown & SSL_RECEIVED_SHUTDOWN) {
1101
0
    s->internal->rwstate = SSL_NOTHING;
1102
0
    rr->length = 0;
1103
0
    return 0;
1104
0
  }
1105
1106
  /* SSL3_RT_APPLICATION_DATA or SSL3_RT_HANDSHAKE */
1107
0
  if (type == rr->type) {
1108
    /*
1109
     * Make sure that we are not getting application data when we
1110
     * are doing a handshake for the first time.
1111
     */
1112
0
    if (SSL_in_init(s) && type == SSL3_RT_APPLICATION_DATA &&
1113
0
        !tls12_record_layer_read_protected(s->internal->rl)) {
1114
0
      SSLerror(s, SSL_R_APP_DATA_IN_HANDSHAKE);
1115
0
      ssl3_send_alert(s, SSL3_AL_FATAL,
1116
0
          SSL_AD_UNEXPECTED_MESSAGE);
1117
0
      return -1;
1118
0
    }
1119
1120
0
    if (len <= 0)
1121
0
      return len;
1122
1123
0
    if ((unsigned int)len > rr->length)
1124
0
      n = rr->length;
1125
0
    else
1126
0
      n = (unsigned int)len;
1127
1128
0
    memcpy(buf, &rr->data[rr->off], n);
1129
0
    if (!peek) {
1130
0
      memset(&rr->data[rr->off], 0, n);
1131
0
      rr->length -= n;
1132
0
      rr->off += n;
1133
0
      if (rr->length == 0) {
1134
0
        s->internal->rstate = SSL_ST_READ_HEADER;
1135
0
        rr->off = 0;
1136
0
        if (s->internal->mode & SSL_MODE_RELEASE_BUFFERS &&
1137
0
            s->s3->rbuf.left == 0)
1138
0
          ssl3_release_read_buffer(s);
1139
0
      }
1140
0
    }
1141
1142
0
    return n;
1143
0
  }
1144
1145
  /*
1146
   * If we get here, then type != rr->type; if we have a handshake
1147
   * message, then it was unexpected (Hello Request or Client Hello).
1148
   */
1149
1150
0
  if (rr->type == SSL3_RT_ALERT) {
1151
0
    if ((ret = ssl3_read_alert(s)) <= 0)
1152
0
      return ret;
1153
0
    goto start;
1154
0
  }
1155
1156
0
  if (s->internal->shutdown & SSL_SENT_SHUTDOWN) {
1157
0
    s->internal->rwstate = SSL_NOTHING;
1158
0
    rr->length = 0;
1159
0
    return 0;
1160
0
  }
1161
1162
0
  if (rr->type == SSL3_RT_APPLICATION_DATA) {
1163
    /*
1164
     * At this point, we were expecting handshake data, but have
1165
     * application data. If the library was running inside
1166
     * ssl3_read() (i.e. in_read_app_data is set) and it makes
1167
     * sense to read application data at this point (session
1168
     * renegotiation not yet started), we will indulge it.
1169
     */
1170
0
    if (s->s3->in_read_app_data != 0 &&
1171
0
        s->s3->total_renegotiations != 0 &&
1172
0
        (((s->s3->hs.state & SSL_ST_CONNECT) &&
1173
0
        (s->s3->hs.state >= SSL3_ST_CW_CLNT_HELLO_A) &&
1174
0
        (s->s3->hs.state <= SSL3_ST_CR_SRVR_HELLO_A)) || (
1175
0
        (s->s3->hs.state & SSL_ST_ACCEPT) &&
1176
0
        (s->s3->hs.state <= SSL3_ST_SW_HELLO_REQ_A) &&
1177
0
        (s->s3->hs.state >= SSL3_ST_SR_CLNT_HELLO_A)))) {
1178
0
      s->s3->in_read_app_data = 2;
1179
0
      return -1;
1180
0
    } else {
1181
0
      SSLerror(s, SSL_R_UNEXPECTED_RECORD);
1182
0
      ssl3_send_alert(s, SSL3_AL_FATAL,
1183
0
          SSL_AD_UNEXPECTED_MESSAGE);
1184
0
      return -1;
1185
0
    }
1186
0
  }
1187
1188
0
  if (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC) {
1189
0
    if ((ret = ssl3_read_change_cipher_spec(s)) <= 0)
1190
0
      return ret;
1191
0
    goto start;
1192
0
  }
1193
1194
0
  if (rr->type == SSL3_RT_HANDSHAKE) {
1195
0
    if ((ret = ssl3_read_handshake_unexpected(s)) <= 0)
1196
0
      return ret;
1197
0
    goto start;
1198
0
  }
1199
1200
  /*
1201
   * Unknown record type - TLSv1.2 sends an unexpected message alert while
1202
   * earlier versions silently ignore the record.
1203
   */
1204
0
  if (ssl_effective_tls_version(s) <= TLS1_1_VERSION) {
1205
0
    rr->length = 0;
1206
0
    goto start;
1207
0
  }
1208
0
  SSLerror(s, SSL_R_UNEXPECTED_RECORD);
1209
0
  ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
1210
0
  return -1;
1211
0
}
1212
1213
int
1214
ssl3_do_change_cipher_spec(SSL *s)
1215
0
{
1216
0
  if (s->s3->hs.tls12.key_block == NULL) {
1217
0
    if (s->session == NULL || s->session->master_key_length == 0) {
1218
      /* might happen if dtls1_read_bytes() calls this */
1219
0
      SSLerror(s, SSL_R_CCS_RECEIVED_EARLY);
1220
0
      return (0);
1221
0
    }
1222
1223
0
    s->session->cipher = s->s3->hs.cipher;
1224
0
    if (!tls1_setup_key_block(s))
1225
0
      return (0);
1226
0
  }
1227
1228
0
  if (!tls1_change_read_cipher_state(s))
1229
0
    return (0);
1230
1231
  /*
1232
   * We have to record the message digest at this point so we can get it
1233
   * before we read the finished message.
1234
   */
1235
0
  if (!tls12_derive_peer_finished(s))
1236
0
    return (0);
1237
1238
0
  return (1);
1239
0
}
1240
1241
static int
1242
ssl3_write_alert(SSL *s)
1243
0
{
1244
0
  if (SSL_is_dtls(s))
1245
0
    return do_dtls1_write(s, SSL3_RT_ALERT, s->s3->send_alert,
1246
0
        sizeof(s->s3->send_alert));
1247
1248
0
  return do_ssl3_write(s, SSL3_RT_ALERT, s->s3->send_alert,
1249
0
      sizeof(s->s3->send_alert));
1250
0
}
1251
1252
int
1253
ssl3_send_alert(SSL *s, int level, int desc)
1254
0
{
1255
  /* If alert is fatal, remove session from cache. */
1256
0
  if (level == SSL3_AL_FATAL)
1257
0
    SSL_CTX_remove_session(s->ctx, s->session);
1258
1259
0
  s->s3->alert_dispatch = 1;
1260
0
  s->s3->send_alert[0] = level;
1261
0
  s->s3->send_alert[1] = desc;
1262
1263
  /*
1264
   * If data is still being written out, the alert will be dispatched at
1265
   * some point in the future.
1266
   */
1267
0
  if (s->s3->wbuf.left != 0)
1268
0
    return -1;
1269
1270
0
  return ssl3_dispatch_alert(s);
1271
0
}
1272
1273
int
1274
ssl3_dispatch_alert(SSL *s)
1275
0
{
1276
0
  int ret;
1277
1278
0
  s->s3->alert_dispatch = 0;
1279
0
  if ((ret = ssl3_write_alert(s)) <= 0) {
1280
0
    s->s3->alert_dispatch = 1;
1281
0
    return ret;
1282
0
  }
1283
1284
  /*
1285
   * Alert sent to BIO.  If it is important, flush it now.
1286
   * If the message does not get sent due to non-blocking IO,
1287
   * we will not worry too much.
1288
   */
1289
0
  if (s->s3->send_alert[0] == SSL3_AL_FATAL)
1290
0
    (void)BIO_flush(s->wbio);
1291
1292
0
  ssl_msg_callback(s, 1, SSL3_RT_ALERT, s->s3->send_alert, 2);
1293
1294
0
  ssl_info_callback(s, SSL_CB_WRITE_ALERT,
1295
0
      (s->s3->send_alert[0] << 8) | s->s3->send_alert[1]);
1296
1297
0
  return ret;
1298
0
}