2 * Copyright 2016 The OpenSSL Project Authors. All Rights Reserved.
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
10 #include "../ssl_locl.h"
11 #include "record_locl.h"
14 * tls13_enc encrypts/decrypts |n_recs| in |recs|.
17 * 0: (in non-constant time) if the record is publically invalid (i.e. too
19 * 1: if the record encryption was successful.
20 * -1: if the record's AEAD-authenticator is invalid or, if sending,
21 * an internal error occurred.
23 int tls13_enc(SSL *s, SSL3_RECORD *recs, size_t n_recs, int send)
26 unsigned char iv[EVP_MAX_IV_LENGTH];
27 size_t ivlen, taglen, offset, loop;
28 unsigned char *staticiv;
31 SSL3_RECORD *rec = &recs[0];
32 uint32_t alg_enc = s->s3->tmp.new_cipher->algorithm_enc;
35 /* Should not happen */
36 /* TODO(TLS1.3): Support pipelining */
41 ctx = s->enc_write_ctx;
42 staticiv = s->write_iv;
43 seq = RECORD_LAYER_get_write_sequence(&s->rlayer);
45 ctx = s->enc_read_ctx;
46 staticiv = s->read_iv;
47 seq = RECORD_LAYER_get_read_sequence(&s->rlayer);
51 memmove(rec->data, rec->input, rec->length);
52 rec->input = rec->data;
55 ivlen = EVP_CIPHER_CTX_iv_length(ctx);
57 if (alg_enc & SSL_AESCCM) {
58 if (alg_enc & (SSL_AES128CCM8 | SSL_AES256CCM8))
59 taglen = EVP_CCM8_TLS_TAG_LEN;
61 taglen = EVP_CCM_TLS_TAG_LEN;
62 if (send && EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_TAG, taglen,
65 } else if (alg_enc & SSL_AESGCM) {
66 taglen = EVP_GCM_TLS_TAG_LEN;
67 } else if (alg_enc & SSL_CHACHA20) {
68 taglen = EVP_CHACHAPOLY_TLS_TAG_LEN;
75 * Take off tag. There must be at least one byte of content type as
78 if (rec->length < taglen + 1)
80 rec->length -= taglen;
84 if (ivlen < SEQ_NUM_SIZE) {
85 /* Should not happen */
88 offset = ivlen - SEQ_NUM_SIZE;
89 memcpy(iv, staticiv, offset);
90 for (loop = 0; loop < SEQ_NUM_SIZE; loop++)
91 iv[offset + loop] = staticiv[offset + loop] ^ seq[loop];
93 /* Increment the sequence counter */
94 for (loop = SEQ_NUM_SIZE; loop > 0; loop--) {
96 if (seq[loop - 1] != 0)
100 /* Sequence has wrapped */
104 /* TODO(size_t): lenu/lenf should be a size_t but EVP doesn't support it */
105 if (EVP_CipherInit_ex(ctx, NULL, NULL, NULL, iv, send) <= 0
106 || (!send && EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_TAG,
108 rec->data + rec->length) <= 0)
109 || EVP_CipherUpdate(ctx, rec->data, &lenu, rec->input,
110 (unsigned int)rec->length) <= 0
111 || EVP_CipherFinal_ex(ctx, rec->data + lenu, &lenf) <= 0
112 || (size_t)(lenu + lenf) != rec->length) {
117 if (EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_GET_TAG, taglen,
118 rec->data + rec->length) <= 0)
120 rec->length += taglen;