1 /**
2  * \brief AES block cipher, ESP32-S2 hardware accelerated version
3  * Based on mbedTLS FIPS-197 compliant version.
4  *
5  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
6  *  Additions Copyright (C) 2016-2020, Espressif Systems (Shanghai) PTE Ltd
7  *  SPDX-License-Identifier: Apache-2.0
8  *
9  *  Licensed under the Apache License, Version 2.0 (the "License"); you may
10  *  not use this file except in compliance with the License.
11  *  You may obtain a copy of the License at
12  *
13  *  http://www.apache.org/licenses/LICENSE-2.0
14  *
15  *  Unless required by applicable law or agreed to in writing, software
16  *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
17  *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  *  See the License for the specific language governing permissions and
19  *  limitations under the License.
20  *
21  */
22 /*
23  *  The AES block cipher was designed by Vincent Rijmen and Joan Daemen.
24  *
25  *  http://csrc.nist.gov/encryption/aes/rijndael/Rijndael.pdf
26  *  http://csrc.nist.gov/publications/fips/fips197/fips-197.pdf
27  */
28 
29 
30 /* Below XTS implementation is copied aes.c of mbedtls library.
31  * When MBEDTLS_AES_ALT is defined mbedtls expects alternate
32  * definition of XTS functions to be available. Even if this
33  * could have been avoided, it is done for consistency reason.
34  */
35 
36 #include <stdio.h>
37 #include <string.h>
38 #include <sys/lock.h>
39 #include "mbedtls/aes.h"
40 
41 #include "aes/esp_aes.h"
42 
esp_aes_xts_init(esp_aes_xts_context * ctx)43 void esp_aes_xts_init( esp_aes_xts_context *ctx )
44 {
45     esp_aes_init( &ctx->crypt );
46     esp_aes_init( &ctx->tweak );
47 }
48 
esp_aes_xts_free(esp_aes_xts_context * ctx)49 void esp_aes_xts_free( esp_aes_xts_context *ctx )
50 {
51     esp_aes_free( &ctx->crypt );
52     esp_aes_free( &ctx->tweak );
53 }
54 
esp_aes_xts_decode_keys(const unsigned char * key,unsigned int keybits,const unsigned char ** key1,unsigned int * key1bits,const unsigned char ** key2,unsigned int * key2bits)55 static int esp_aes_xts_decode_keys( const unsigned char *key,
56                                     unsigned int keybits,
57                                     const unsigned char **key1,
58                                     unsigned int *key1bits,
59                                     const unsigned char **key2,
60                                     unsigned int *key2bits )
61 {
62     const unsigned int half_keybits = keybits / 2;
63     const unsigned int half_keybytes = half_keybits / 8;
64 
65     switch ( keybits ) {
66     case 256: break;
67     case 512: break;
68     default : return ( MBEDTLS_ERR_AES_INVALID_KEY_LENGTH );
69     }
70 
71     *key1bits = half_keybits;
72     *key2bits = half_keybits;
73     *key1 = &key[0];
74     *key2 = &key[half_keybytes];
75 
76     return 0;
77 }
78 
esp_aes_xts_setkey_enc(esp_aes_xts_context * ctx,const unsigned char * key,unsigned int keybits)79 int esp_aes_xts_setkey_enc( esp_aes_xts_context *ctx,
80                             const unsigned char *key,
81                             unsigned int keybits)
82 {
83     int ret;
84     const unsigned char *key1, *key2;
85     unsigned int key1bits, key2bits;
86 
87     ret = esp_aes_xts_decode_keys( key, keybits, &key1, &key1bits,
88                                    &key2, &key2bits );
89     if ( ret != 0 ) {
90         return ( ret );
91     }
92 
93     /* Set the tweak key. Always set tweak key for the encryption mode. */
94     ret = esp_aes_setkey( &ctx->tweak, key2, key2bits );
95     if ( ret != 0 ) {
96         return ( ret );
97     }
98 
99     /* Set crypt key for encryption. */
100     return esp_aes_setkey( &ctx->crypt, key1, key1bits );
101 }
102 
esp_aes_xts_setkey_dec(esp_aes_xts_context * ctx,const unsigned char * key,unsigned int keybits)103 int esp_aes_xts_setkey_dec( esp_aes_xts_context *ctx,
104                             const unsigned char *key,
105                             unsigned int keybits)
106 {
107     int ret;
108     const unsigned char *key1, *key2;
109     unsigned int key1bits, key2bits;
110 
111     ret = esp_aes_xts_decode_keys( key, keybits, &key1, &key1bits,
112                                    &key2, &key2bits );
113     if ( ret != 0 ) {
114         return ( ret );
115     }
116 
117     /* Set the tweak key. Always set tweak key for encryption. */
118     ret = esp_aes_setkey( &ctx->tweak, key2, key2bits );
119     if ( ret != 0 ) {
120         return ( ret );
121     }
122 
123     /* Set crypt key for decryption. */
124     return esp_aes_setkey( &ctx->crypt, key1, key1bits );
125 }
126 
127 /* Endianess with 64 bits values */
128 #ifndef GET_UINT64_LE
129 #define GET_UINT64_LE(n,b,i)                            \
130 {                                                       \
131     (n) = ( (uint64_t) (b)[(i) + 7] << 56 )             \
132         | ( (uint64_t) (b)[(i) + 6] << 48 )             \
133         | ( (uint64_t) (b)[(i) + 5] << 40 )             \
134         | ( (uint64_t) (b)[(i) + 4] << 32 )             \
135         | ( (uint64_t) (b)[(i) + 3] << 24 )             \
136         | ( (uint64_t) (b)[(i) + 2] << 16 )             \
137         | ( (uint64_t) (b)[(i) + 1] <<  8 )             \
138         | ( (uint64_t) (b)[(i)    ]       );            \
139 }
140 #endif
141 
142 #ifndef PUT_UINT64_LE
143 #define PUT_UINT64_LE(n,b,i)                            \
144 {                                                       \
145     (b)[(i) + 7] = (unsigned char) ( (n) >> 56 );       \
146     (b)[(i) + 6] = (unsigned char) ( (n) >> 48 );       \
147     (b)[(i) + 5] = (unsigned char) ( (n) >> 40 );       \
148     (b)[(i) + 4] = (unsigned char) ( (n) >> 32 );       \
149     (b)[(i) + 3] = (unsigned char) ( (n) >> 24 );       \
150     (b)[(i) + 2] = (unsigned char) ( (n) >> 16 );       \
151     (b)[(i) + 1] = (unsigned char) ( (n) >>  8 );       \
152     (b)[(i)    ] = (unsigned char) ( (n)       );       \
153 }
154 #endif
155 
156 /*
157  * GF(2^128) multiplication function
158  *
159  * This function multiplies a field element by x in the polynomial field
160  * representation. It uses 64-bit word operations to gain speed but compensates
161  * for machine endianess and hence works correctly on both big and little
162  * endian machines.
163  */
esp_gf128mul_x_ble(unsigned char r[16],const unsigned char x[16])164 static void esp_gf128mul_x_ble( unsigned char r[16],
165                                 const unsigned char x[16] )
166 {
167     uint64_t a, b, ra, rb;
168 
169     GET_UINT64_LE( a, x, 0 );
170     GET_UINT64_LE( b, x, 8 );
171 
172     ra = ( a << 1 )  ^ 0x0087 >> ( 8 - ( ( b >> 63 ) << 3 ) );
173     rb = ( a >> 63 ) | ( b << 1 );
174 
175     PUT_UINT64_LE( ra, r, 0 );
176     PUT_UINT64_LE( rb, r, 8 );
177 }
178 
179 /*
180  * AES-XTS buffer encryption/decryption
181  */
esp_aes_crypt_xts(esp_aes_xts_context * ctx,int mode,size_t length,const unsigned char data_unit[16],const unsigned char * input,unsigned char * output)182 int esp_aes_crypt_xts( esp_aes_xts_context *ctx,
183                        int mode,
184                        size_t length,
185                        const unsigned char data_unit[16],
186                        const unsigned char *input,
187                        unsigned char *output )
188 {
189     int ret;
190     size_t blocks = length / 16;
191     size_t leftover = length % 16;
192     unsigned char tweak[16];
193     unsigned char prev_tweak[16];
194     unsigned char tmp[16];
195 
196     /* Sectors must be at least 16 bytes. */
197     if ( length < 16 ) {
198         return MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH;
199     }
200 
201     /* NIST SP 80-38E disallows data units larger than 2**20 blocks. */
202     if ( length > ( 1 << 20 ) * 16 ) {
203         return MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH;
204     }
205 
206     /* Compute the tweak. */
207     ret = esp_aes_crypt_ecb( &ctx->tweak, MBEDTLS_AES_ENCRYPT,
208                              data_unit, tweak );
209     if ( ret != 0 ) {
210         return ( ret );
211     }
212 
213     while ( blocks-- ) {
214         size_t i;
215 
216         if ( leftover && ( mode == MBEDTLS_AES_DECRYPT ) && blocks == 0 ) {
217             /* We are on the last block in a decrypt operation that has
218              * leftover bytes, so we need to use the next tweak for this block,
219              * and this tweak for the lefover bytes. Save the current tweak for
220              * the leftovers and then update the current tweak for use on this,
221              * the last full block. */
222             memcpy( prev_tweak, tweak, sizeof( tweak ) );
223             esp_gf128mul_x_ble( tweak, tweak );
224         }
225 
226         for ( i = 0; i < 16; i++ ) {
227             tmp[i] = input[i] ^ tweak[i];
228         }
229 
230         ret = esp_aes_crypt_ecb( &ctx->crypt, mode, tmp, tmp );
231         if ( ret != 0 ) {
232             return ( ret );
233         }
234 
235         for ( i = 0; i < 16; i++ ) {
236             output[i] = tmp[i] ^ tweak[i];
237         }
238 
239         /* Update the tweak for the next block. */
240         esp_gf128mul_x_ble( tweak, tweak );
241 
242         output += 16;
243         input += 16;
244     }
245 
246     if ( leftover ) {
247         /* If we are on the leftover bytes in a decrypt operation, we need to
248          * use the previous tweak for these bytes (as saved in prev_tweak). */
249         unsigned char *t = mode == MBEDTLS_AES_DECRYPT ? prev_tweak : tweak;
250 
251         /* We are now on the final part of the data unit, which doesn't divide
252          * evenly by 16. It's time for ciphertext stealing. */
253         size_t i;
254         unsigned char *prev_output = output - 16;
255 
256         /* Copy ciphertext bytes from the previous block to our output for each
257          * byte of cyphertext we won't steal. At the same time, copy the
258          * remainder of the input for this final round (since the loop bounds
259          * are the same). */
260         for ( i = 0; i < leftover; i++ ) {
261             output[i] = prev_output[i];
262             tmp[i] = input[i] ^ t[i];
263         }
264 
265         /* Copy ciphertext bytes from the previous block for input in this
266          * round. */
267         for ( ; i < 16; i++ ) {
268             tmp[i] = prev_output[i] ^ t[i];
269         }
270 
271         ret = esp_aes_crypt_ecb( &ctx->crypt, mode, tmp, tmp );
272         if ( ret != 0 ) {
273             return ret;
274         }
275 
276         /* Write the result back to the previous block, overriding the previous
277          * output we copied. */
278         for ( i = 0; i < 16; i++ ) {
279             prev_output[i] = tmp[i] ^ t[i];
280         }
281     }
282 
283     return ( 0 );
284 }
285