1/*
2 * Copyright 2016-2018 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 "../ssl_local.h"
11#include "record_local.h"
12#include "internal/cryptlib.h"
13
14/*-
15 * tls13_enc encrypts/decrypts |n_recs| in |recs|. Will call SSLfatal() for
16 * internal errors, but not otherwise.
17 *
18 * Returns:
19 *    0: (in non-constant time) if the record is publicly invalid (i.e. too
20 *        short etc).
21 *    1: if the record encryption was successful.
22 *   -1: if the record's AEAD-authenticator is invalid or, if sending,
23 *       an internal error occurred.
24 */
25int tls13_enc(SSL *s, SSL3_RECORD *recs, size_t n_recs, int sending)
26{
27    EVP_CIPHER_CTX *ctx;
28    unsigned char iv[EVP_MAX_IV_LENGTH], recheader[SSL3_RT_HEADER_LENGTH];
29    size_t ivlen, taglen, offset, loop, hdrlen;
30    unsigned char *staticiv;
31    unsigned char *seq;
32    int lenu, lenf;
33    SSL3_RECORD *rec = &recs[0];
34    uint32_t alg_enc;
35    WPACKET wpkt;
36
37    if (n_recs != 1) {
38        /* Should not happen */
39        /* TODO(TLS1.3): Support pipelining */
40        SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS13_ENC,
41                 ERR_R_INTERNAL_ERROR);
42        return -1;
43    }
44
45    if (sending) {
46        ctx = s->enc_write_ctx;
47        staticiv = s->write_iv;
48        seq = RECORD_LAYER_get_write_sequence(&s->rlayer);
49    } else {
50        ctx = s->enc_read_ctx;
51        staticiv = s->read_iv;
52        seq = RECORD_LAYER_get_read_sequence(&s->rlayer);
53    }
54
55    /*
56     * If we're sending an alert and ctx != NULL then we must be forcing
57     * plaintext alerts. If we're reading and ctx != NULL then we allow
58     * plaintext alerts at certain points in the handshake. If we've got this
59     * far then we have already validated that a plaintext alert is ok here.
60     */
61    if (ctx == NULL || rec->type == SSL3_RT_ALERT) {
62        memmove(rec->data, rec->input, rec->length);
63        rec->input = rec->data;
64        return 1;
65    }
66
67    ivlen = EVP_CIPHER_CTX_iv_length(ctx);
68
69    if (s->early_data_state == SSL_EARLY_DATA_WRITING
70            || s->early_data_state == SSL_EARLY_DATA_WRITE_RETRY) {
71        if (s->session != NULL && s->session->ext.max_early_data > 0) {
72            alg_enc = s->session->cipher->algorithm_enc;
73        } else {
74            if (!ossl_assert(s->psksession != NULL
75                             && s->psksession->ext.max_early_data > 0)) {
76                SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS13_ENC,
77                         ERR_R_INTERNAL_ERROR);
78                return -1;
79            }
80            alg_enc = s->psksession->cipher->algorithm_enc;
81        }
82    } else {
83        /*
84         * To get here we must have selected a ciphersuite - otherwise ctx would
85         * be NULL
86         */
87        if (!ossl_assert(s->s3->tmp.new_cipher != NULL)) {
88            SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS13_ENC,
89                     ERR_R_INTERNAL_ERROR);
90            return -1;
91        }
92        alg_enc = s->s3->tmp.new_cipher->algorithm_enc;
93    }
94
95    if (alg_enc & SSL_AESCCM) {
96        if (alg_enc & (SSL_AES128CCM8 | SSL_AES256CCM8))
97            taglen = EVP_CCM8_TLS_TAG_LEN;
98         else
99            taglen = EVP_CCM_TLS_TAG_LEN;
100         if (sending && EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_TAG, taglen,
101                                         NULL) <= 0) {
102            SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS13_ENC,
103                     ERR_R_INTERNAL_ERROR);
104            return -1;
105        }
106    } else if (alg_enc & SSL_AESGCM) {
107        taglen = EVP_GCM_TLS_TAG_LEN;
108    } else if (alg_enc & SSL_CHACHA20) {
109        taglen = EVP_CHACHAPOLY_TLS_TAG_LEN;
110    } else {
111        SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS13_ENC,
112                 ERR_R_INTERNAL_ERROR);
113        return -1;
114    }
115
116    if (!sending) {
117        /*
118         * Take off tag. There must be at least one byte of content type as
119         * well as the tag
120         */
121        if (rec->length < taglen + 1)
122            return 0;
123        rec->length -= taglen;
124    }
125
126    /* Set up IV */
127    if (ivlen < SEQ_NUM_SIZE) {
128        /* Should not happen */
129        SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS13_ENC,
130                 ERR_R_INTERNAL_ERROR);
131        return -1;
132    }
133    offset = ivlen - SEQ_NUM_SIZE;
134    memcpy(iv, staticiv, offset);
135    for (loop = 0; loop < SEQ_NUM_SIZE; loop++)
136        iv[offset + loop] = staticiv[offset + loop] ^ seq[loop];
137
138    /* Increment the sequence counter */
139    for (loop = SEQ_NUM_SIZE; loop > 0; loop--) {
140        ++seq[loop - 1];
141        if (seq[loop - 1] != 0)
142            break;
143    }
144    if (loop == 0) {
145        /* Sequence has wrapped */
146        return -1;
147    }
148
149    /* TODO(size_t): lenu/lenf should be a size_t but EVP doesn't support it */
150    if (EVP_CipherInit_ex(ctx, NULL, NULL, NULL, iv, sending) <= 0
151            || (!sending && EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_TAG,
152                                             taglen,
153                                             rec->data + rec->length) <= 0)) {
154        return -1;
155    }
156
157    /* Set up the AAD */
158    if (!WPACKET_init_static_len(&wpkt, recheader, sizeof(recheader), 0)
159            || !WPACKET_put_bytes_u8(&wpkt, rec->type)
160            || !WPACKET_put_bytes_u16(&wpkt, rec->rec_version)
161            || !WPACKET_put_bytes_u16(&wpkt, rec->length + taglen)
162            || !WPACKET_get_total_written(&wpkt, &hdrlen)
163            || hdrlen != SSL3_RT_HEADER_LENGTH
164            || !WPACKET_finish(&wpkt)) {
165        WPACKET_cleanup(&wpkt);
166        return -1;
167    }
168
169    /*
170     * For CCM we must explicitly set the total plaintext length before we add
171     * any AAD.
172     */
173    if (((alg_enc & SSL_AESCCM) != 0
174                 && EVP_CipherUpdate(ctx, NULL, &lenu, NULL,
175                                     (unsigned int)rec->length) <= 0)
176            || EVP_CipherUpdate(ctx, NULL, &lenu, recheader,
177                                sizeof(recheader)) <= 0
178            || EVP_CipherUpdate(ctx, rec->data, &lenu, rec->input,
179                                (unsigned int)rec->length) <= 0
180            || EVP_CipherFinal_ex(ctx, rec->data + lenu, &lenf) <= 0
181            || (size_t)(lenu + lenf) != rec->length) {
182        return -1;
183    }
184    if (sending) {
185        /* Add the tag */
186        if (EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_GET_TAG, taglen,
187                                rec->data + rec->length) <= 0) {
188            SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS13_ENC,
189                     ERR_R_INTERNAL_ERROR);
190            return -1;
191        }
192        rec->length += taglen;
193    }
194
195    return 1;
196}
197