Path: blob/master/thirdparty/mbedtls/library/aesce.c
10278 views
/*1* Armv8-A Cryptographic Extension support functions for Aarch642*3* Copyright The Mbed TLS Contributors4* SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later5*/67#if defined(__clang__) && (__clang_major__ >= 4)89/* Ideally, we would simply use MBEDTLS_ARCH_IS_ARMV8_A in the following #if,10* but that is defined by build_info.h, and we need this block to happen first. */11#if defined(__ARM_ARCH)12#if __ARM_ARCH >= 813#define MBEDTLS_AESCE_ARCH_IS_ARMV8_A14#endif15#endif1617#if defined(MBEDTLS_AESCE_ARCH_IS_ARMV8_A) && !defined(__ARM_FEATURE_CRYPTO)18/* TODO: Re-consider above after https://reviews.llvm.org/D131064 merged.19*20* The intrinsic declaration are guarded by predefined ACLE macros in clang:21* these are normally only enabled by the -march option on the command line.22* By defining the macros ourselves we gain access to those declarations without23* requiring -march on the command line.24*25* `arm_neon.h` is included by common.h, so we put these defines26* at the top of this file, before any includes.27*/28#define __ARM_FEATURE_CRYPTO 129/* See: https://arm-software.github.io/acle/main/acle.html#cryptographic-extensions30*31* `__ARM_FEATURE_CRYPTO` is deprecated, but we need to continue to specify it32* for older compilers.33*/34#define __ARM_FEATURE_AES 135#define MBEDTLS_ENABLE_ARM_CRYPTO_EXTENSIONS_COMPILER_FLAG36#endif3738#endif /* defined(__clang__) && (__clang_major__ >= 4) */3940#include <string.h>41#include "common.h"4243#if defined(MBEDTLS_AESCE_C)4445#include "aesce.h"4647#if defined(MBEDTLS_AESCE_HAVE_CODE)4849/* Compiler version checks. */50#if defined(__clang__)51# if defined(MBEDTLS_ARCH_IS_ARM32) && (__clang_major__ < 11)52# error "Minimum version of Clang for MBEDTLS_AESCE_C on 32-bit Arm or Thumb is 11.0."53# elif defined(MBEDTLS_ARCH_IS_ARM64) && (__clang_major__ < 4)54# error "Minimum version of Clang for MBEDTLS_AESCE_C on aarch64 is 4.0."55# endif56#elif defined(__GNUC__)57# if __GNUC__ < 658# error "Minimum version of GCC for MBEDTLS_AESCE_C is 6.0."59# endif60#elif defined(_MSC_VER)61/* TODO: We haven't verified MSVC from 1920 to 1928. If someone verified that,62* please update this and document of `MBEDTLS_AESCE_C` in63* `mbedtls_config.h`. */64# if _MSC_VER < 192965# error "Minimum version of MSVC for MBEDTLS_AESCE_C is 2019 version 16.11.2."66# endif67#elif defined(__ARMCC_VERSION)68# if defined(MBEDTLS_ARCH_IS_ARM32) && (__ARMCC_VERSION < 6200002)69/* TODO: We haven't verified armclang for 32-bit Arm/Thumb prior to 6.20.70* If someone verified that, please update this and document of71* `MBEDTLS_AESCE_C` in `mbedtls_config.h`. */72# error "Minimum version of armclang for MBEDTLS_AESCE_C on 32-bit Arm is 6.20."73# elif defined(MBEDTLS_ARCH_IS_ARM64) && (__ARMCC_VERSION < 6060000)74# error "Minimum version of armclang for MBEDTLS_AESCE_C on aarch64 is 6.6."75# endif76#endif7778#if !(defined(__ARM_FEATURE_CRYPTO) || defined(__ARM_FEATURE_AES)) || \79defined(MBEDTLS_ENABLE_ARM_CRYPTO_EXTENSIONS_COMPILER_FLAG)80# if defined(__ARMCOMPILER_VERSION)81# if __ARMCOMPILER_VERSION <= 609000082# error "Must use minimum -march=armv8-a+crypto for MBEDTLS_AESCE_C"83# else84# pragma clang attribute push (__attribute__((target("aes"))), apply_to=function)85# define MBEDTLS_POP_TARGET_PRAGMA86# endif87# elif defined(__clang__)88# pragma clang attribute push (__attribute__((target("aes"))), apply_to=function)89# define MBEDTLS_POP_TARGET_PRAGMA90# elif defined(__GNUC__)91# pragma GCC push_options92# pragma GCC target ("+crypto")93# define MBEDTLS_POP_TARGET_PRAGMA94# elif defined(_MSC_VER)95# error "Required feature(__ARM_FEATURE_AES) is not enabled."96# endif97#endif /* !(__ARM_FEATURE_CRYPTO || __ARM_FEATURE_AES) ||98MBEDTLS_ENABLE_ARM_CRYPTO_EXTENSIONS_COMPILER_FLAG */99100#if defined(__linux__) && !defined(MBEDTLS_AES_USE_HARDWARE_ONLY)101102#include <sys/auxv.h>103#if !defined(HWCAP_NEON)104#define HWCAP_NEON (1 << 12)105#endif106#if !defined(HWCAP2_AES)107#define HWCAP2_AES (1 << 0)108#endif109#if !defined(HWCAP_AES)110#define HWCAP_AES (1 << 3)111#endif112#if !defined(HWCAP_ASIMD)113#define HWCAP_ASIMD (1 << 1)114#endif115116signed char mbedtls_aesce_has_support_result = -1;117118#if !defined(MBEDTLS_AES_USE_HARDWARE_ONLY)119/*120* AES instruction support detection routine121*/122int mbedtls_aesce_has_support_impl(void)123{124/* To avoid many calls to getauxval, cache the result. This is125* thread-safe, because we store the result in a char so cannot126* be vulnerable to non-atomic updates.127* It is possible that we could end up setting result more than128* once, but that is harmless.129*/130if (mbedtls_aesce_has_support_result == -1) {131#if defined(MBEDTLS_ARCH_IS_ARM32)132unsigned long auxval = getauxval(AT_HWCAP);133unsigned long auxval2 = getauxval(AT_HWCAP2);134if (((auxval & HWCAP_NEON) == HWCAP_NEON) &&135((auxval2 & HWCAP2_AES) == HWCAP2_AES)) {136mbedtls_aesce_has_support_result = 1;137} else {138mbedtls_aesce_has_support_result = 0;139}140#else141unsigned long auxval = getauxval(AT_HWCAP);142if ((auxval & (HWCAP_ASIMD | HWCAP_AES)) ==143(HWCAP_ASIMD | HWCAP_AES)) {144mbedtls_aesce_has_support_result = 1;145} else {146mbedtls_aesce_has_support_result = 0;147}148#endif149}150return mbedtls_aesce_has_support_result;151}152#endif153154#endif /* defined(__linux__) && !defined(MBEDTLS_AES_USE_HARDWARE_ONLY) */155156/* Single round of AESCE encryption */157#define AESCE_ENCRYPT_ROUND \158block = vaeseq_u8(block, vld1q_u8(keys)); \159block = vaesmcq_u8(block); \160keys += 16161/* Two rounds of AESCE encryption */162#define AESCE_ENCRYPT_ROUND_X2 AESCE_ENCRYPT_ROUND; AESCE_ENCRYPT_ROUND163164MBEDTLS_OPTIMIZE_FOR_PERFORMANCE165static uint8x16_t aesce_encrypt_block(uint8x16_t block,166unsigned char *keys,167int rounds)168{169/* 10, 12 or 14 rounds. Unroll loop. */170if (rounds == 10) {171goto rounds_10;172}173if (rounds == 12) {174goto rounds_12;175}176AESCE_ENCRYPT_ROUND_X2;177rounds_12:178AESCE_ENCRYPT_ROUND_X2;179rounds_10:180AESCE_ENCRYPT_ROUND_X2;181AESCE_ENCRYPT_ROUND_X2;182AESCE_ENCRYPT_ROUND_X2;183AESCE_ENCRYPT_ROUND_X2;184AESCE_ENCRYPT_ROUND;185186/* AES AddRoundKey for the previous round.187* SubBytes, ShiftRows for the final round. */188block = vaeseq_u8(block, vld1q_u8(keys));189keys += 16;190191/* Final round: no MixColumns */192193/* Final AddRoundKey */194block = veorq_u8(block, vld1q_u8(keys));195196return block;197}198199/* Single round of AESCE decryption200*201* AES AddRoundKey, SubBytes, ShiftRows202*203* block = vaesdq_u8(block, vld1q_u8(keys));204*205* AES inverse MixColumns for the next round.206*207* This means that we switch the order of the inverse AddRoundKey and208* inverse MixColumns operations. We have to do this as AddRoundKey is209* done in an atomic instruction together with the inverses of SubBytes210* and ShiftRows.211*212* It works because MixColumns is a linear operation over GF(2^8) and213* AddRoundKey is an exclusive or, which is equivalent to addition over214* GF(2^8). (The inverse of MixColumns needs to be applied to the215* affected round keys separately which has been done when the216* decryption round keys were calculated.)217*218* block = vaesimcq_u8(block);219*/220#define AESCE_DECRYPT_ROUND \221block = vaesdq_u8(block, vld1q_u8(keys)); \222block = vaesimcq_u8(block); \223keys += 16224/* Two rounds of AESCE decryption */225#define AESCE_DECRYPT_ROUND_X2 AESCE_DECRYPT_ROUND; AESCE_DECRYPT_ROUND226227#if !defined(MBEDTLS_BLOCK_CIPHER_NO_DECRYPT)228static uint8x16_t aesce_decrypt_block(uint8x16_t block,229unsigned char *keys,230int rounds)231{232/* 10, 12 or 14 rounds. Unroll loop. */233if (rounds == 10) {234goto rounds_10;235}236if (rounds == 12) {237goto rounds_12;238}239AESCE_DECRYPT_ROUND_X2;240rounds_12:241AESCE_DECRYPT_ROUND_X2;242rounds_10:243AESCE_DECRYPT_ROUND_X2;244AESCE_DECRYPT_ROUND_X2;245AESCE_DECRYPT_ROUND_X2;246AESCE_DECRYPT_ROUND_X2;247AESCE_DECRYPT_ROUND;248249/* The inverses of AES AddRoundKey, SubBytes, ShiftRows finishing up the250* last full round. */251block = vaesdq_u8(block, vld1q_u8(keys));252keys += 16;253254/* Inverse AddRoundKey for inverting the initial round key addition. */255block = veorq_u8(block, vld1q_u8(keys));256257return block;258}259#endif260261/*262* AES-ECB block en(de)cryption263*/264int mbedtls_aesce_crypt_ecb(mbedtls_aes_context *ctx,265int mode,266const unsigned char input[16],267unsigned char output[16])268{269uint8x16_t block = vld1q_u8(&input[0]);270unsigned char *keys = (unsigned char *) (ctx->buf + ctx->rk_offset);271272#if !defined(MBEDTLS_BLOCK_CIPHER_NO_DECRYPT)273if (mode == MBEDTLS_AES_DECRYPT) {274block = aesce_decrypt_block(block, keys, ctx->nr);275} else276#else277(void) mode;278#endif279{280block = aesce_encrypt_block(block, keys, ctx->nr);281}282vst1q_u8(&output[0], block);283284return 0;285}286287/*288* Compute decryption round keys from encryption round keys289*/290#if !defined(MBEDTLS_BLOCK_CIPHER_NO_DECRYPT)291void mbedtls_aesce_inverse_key(unsigned char *invkey,292const unsigned char *fwdkey,293int nr)294{295int i, j;296j = nr;297vst1q_u8(invkey, vld1q_u8(fwdkey + j * 16));298for (i = 1, j--; j > 0; i++, j--) {299vst1q_u8(invkey + i * 16,300vaesimcq_u8(vld1q_u8(fwdkey + j * 16)));301}302vst1q_u8(invkey + i * 16, vld1q_u8(fwdkey + j * 16));303304}305#endif306307static inline uint32_t aes_rot_word(uint32_t word)308{309return (word << (32 - 8)) | (word >> 8);310}311312static inline uint32_t aes_sub_word(uint32_t in)313{314uint8x16_t v = vreinterpretq_u8_u32(vdupq_n_u32(in));315uint8x16_t zero = vdupq_n_u8(0);316317/* vaeseq_u8 does both SubBytes and ShiftRows. Taking the first row yields318* the correct result as ShiftRows doesn't change the first row. */319v = vaeseq_u8(zero, v);320return vgetq_lane_u32(vreinterpretq_u32_u8(v), 0);321}322323/*324* Key expansion function325*/326static void aesce_setkey_enc(unsigned char *rk,327const unsigned char *key,328const size_t key_bit_length)329{330static uint8_t const rcon[] = { 0x01, 0x02, 0x04, 0x08, 0x10,3310x20, 0x40, 0x80, 0x1b, 0x36 };332/* See https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.197.pdf333* - Section 5, Nr = Nk + 6334* - Section 5.2, the length of round keys is Nb*(Nr+1)335*/336const size_t key_len_in_words = key_bit_length / 32; /* Nk */337const size_t round_key_len_in_words = 4; /* Nb */338const size_t rounds_needed = key_len_in_words + 6; /* Nr */339const size_t round_keys_len_in_words =340round_key_len_in_words * (rounds_needed + 1); /* Nb*(Nr+1) */341const uint32_t *rko_end = (uint32_t *) rk + round_keys_len_in_words;342343memcpy(rk, key, key_len_in_words * 4);344345for (uint32_t *rki = (uint32_t *) rk;346rki + key_len_in_words < rko_end;347rki += key_len_in_words) {348349size_t iteration = (size_t) (rki - (uint32_t *) rk) / key_len_in_words;350uint32_t *rko;351rko = rki + key_len_in_words;352rko[0] = aes_rot_word(aes_sub_word(rki[key_len_in_words - 1]));353rko[0] ^= rcon[iteration] ^ rki[0];354rko[1] = rko[0] ^ rki[1];355rko[2] = rko[1] ^ rki[2];356rko[3] = rko[2] ^ rki[3];357if (rko + key_len_in_words > rko_end) {358/* Do not write overflow words.*/359continue;360}361#if !defined(MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH)362switch (key_bit_length) {363case 128:364break;365case 192:366rko[4] = rko[3] ^ rki[4];367rko[5] = rko[4] ^ rki[5];368break;369case 256:370rko[4] = aes_sub_word(rko[3]) ^ rki[4];371rko[5] = rko[4] ^ rki[5];372rko[6] = rko[5] ^ rki[6];373rko[7] = rko[6] ^ rki[7];374break;375}376#endif /* !MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH */377}378}379380/*381* Key expansion, wrapper382*/383int mbedtls_aesce_setkey_enc(unsigned char *rk,384const unsigned char *key,385size_t bits)386{387switch (bits) {388case 128:389case 192:390case 256:391aesce_setkey_enc(rk, key, bits);392break;393default:394return MBEDTLS_ERR_AES_INVALID_KEY_LENGTH;395}396397return 0;398}399400#if defined(MBEDTLS_GCM_C)401402#if defined(MBEDTLS_ARCH_IS_ARM32)403404#if defined(__clang__)405/* On clang for A32/T32, work around some missing intrinsics and types which are listed in406* [ACLE](https://arm-software.github.io/acle/neon_intrinsics/advsimd.html#polynomial-1)407* These are only required for GCM.408*/409#define vreinterpretq_u64_p64(a) ((uint64x2_t) a)410411typedef uint8x16_t poly128_t;412413static inline poly128_t vmull_p64(poly64_t a, poly64_t b)414{415poly128_t r;416asm ("vmull.p64 %[r], %[a], %[b]" : [r] "=w" (r) : [a] "w" (a), [b] "w" (b) :);417return r;418}419420/* This is set to cause some more missing intrinsics to be defined below */421#define COMMON_MISSING_INTRINSICS422423static inline poly128_t vmull_high_p64(poly64x2_t a, poly64x2_t b)424{425return vmull_p64((poly64_t) (vget_high_u64((uint64x2_t) a)),426(poly64_t) (vget_high_u64((uint64x2_t) b)));427}428429#endif /* defined(__clang__) */430431static inline uint8x16_t vrbitq_u8(uint8x16_t x)432{433/* There is no vrbitq_u8 instruction in A32/T32, so provide434* an equivalent non-Neon implementation. Reverse bit order in each435* byte with 4x rbit, rev. */436asm ("ldm %[p], { r2-r5 } \n\t"437"rbit r2, r2 \n\t"438"rev r2, r2 \n\t"439"rbit r3, r3 \n\t"440"rev r3, r3 \n\t"441"rbit r4, r4 \n\t"442"rev r4, r4 \n\t"443"rbit r5, r5 \n\t"444"rev r5, r5 \n\t"445"stm %[p], { r2-r5 } \n\t"446:447/* Output: 16 bytes of memory pointed to by &x */448"+m" (*(uint8_t(*)[16]) &x)449:450[p] "r" (&x)451:452"r2", "r3", "r4", "r5"453);454return x;455}456457#endif /* defined(MBEDTLS_ARCH_IS_ARM32) */458459#if defined(MBEDTLS_COMPILER_IS_GCC) && __GNUC__ == 5460/* Some intrinsics are not available for GCC 5.X. */461#define COMMON_MISSING_INTRINSICS462#endif /* MBEDTLS_COMPILER_IS_GCC && __GNUC__ == 5 */463464465#if defined(COMMON_MISSING_INTRINSICS)466467/* Missing intrinsics common to both GCC 5, and Clang on 32-bit */468469#define vreinterpretq_p64_u8(a) ((poly64x2_t) a)470#define vreinterpretq_u8_p128(a) ((uint8x16_t) a)471472static inline poly64x1_t vget_low_p64(poly64x2_t a)473{474uint64x1_t r = vget_low_u64(vreinterpretq_u64_p64(a));475return (poly64x1_t) r;476477}478479#endif /* COMMON_MISSING_INTRINSICS */480481/* vmull_p64/vmull_high_p64 wrappers.482*483* Older compilers miss some intrinsic functions for `poly*_t`. We use484* uint8x16_t and uint8x16x3_t as input/output parameters.485*/486#if defined(MBEDTLS_COMPILER_IS_GCC)487/* GCC reports incompatible type error without cast. GCC think poly64_t and488* poly64x1_t are different, that is different with MSVC and Clang. */489#define MBEDTLS_VMULL_P64(a, b) vmull_p64((poly64_t) a, (poly64_t) b)490#else491/* MSVC reports `error C2440: 'type cast'` with cast. Clang does not report492* error with/without cast. And I think poly64_t and poly64x1_t are same, no493* cast for clang also. */494#define MBEDTLS_VMULL_P64(a, b) vmull_p64(a, b)495#endif /* MBEDTLS_COMPILER_IS_GCC */496497static inline uint8x16_t pmull_low(uint8x16_t a, uint8x16_t b)498{499500return vreinterpretq_u8_p128(501MBEDTLS_VMULL_P64(502(poly64_t) vget_low_p64(vreinterpretq_p64_u8(a)),503(poly64_t) vget_low_p64(vreinterpretq_p64_u8(b))504));505}506507static inline uint8x16_t pmull_high(uint8x16_t a, uint8x16_t b)508{509return vreinterpretq_u8_p128(510vmull_high_p64(vreinterpretq_p64_u8(a),511vreinterpretq_p64_u8(b)));512}513514/* GHASH does 128b polynomial multiplication on block in GF(2^128) defined by515* `x^128 + x^7 + x^2 + x + 1`.516*517* Arm64 only has 64b->128b polynomial multipliers, we need to do 4 64b518* multiplies to generate a 128b.519*520* `poly_mult_128` executes polynomial multiplication and outputs 256b that521* represented by 3 128b due to code size optimization.522*523* Output layout:524* | | | |525* |------------|-------------|-------------|526* | ret.val[0] | h3:h2:00:00 | high 128b |527* | ret.val[1] | :m2:m1:00 | middle 128b |528* | ret.val[2] | : :l1:l0 | low 128b |529*/530static inline uint8x16x3_t poly_mult_128(uint8x16_t a, uint8x16_t b)531{532uint8x16x3_t ret;533uint8x16_t h, m, l; /* retval high/middle/low */534uint8x16_t c, d, e;535536h = pmull_high(a, b); /* h3:h2:00:00 = a1*b1 */537l = pmull_low(a, b); /* : :l1:l0 = a0*b0 */538c = vextq_u8(b, b, 8); /* :c1:c0 = b0:b1 */539d = pmull_high(a, c); /* :d2:d1:00 = a1*b0 */540e = pmull_low(a, c); /* :e2:e1:00 = a0*b1 */541m = veorq_u8(d, e); /* :m2:m1:00 = d + e */542543ret.val[0] = h;544ret.val[1] = m;545ret.val[2] = l;546return ret;547}548549/*550* Modulo reduction.551*552* See: https://www.researchgate.net/publication/285612706_Implementing_GCM_on_ARMv8553*554* Section 4.3555*556* Modular reduction is slightly more complex. Write the GCM modulus as f(z) =557* z^128 +r(z), where r(z) = z^7+z^2+z+ 1. The well known approach is to558* consider that z^128 ≡r(z) (mod z^128 +r(z)), allowing us to write the 256-bit559* operand to be reduced as a(z) = h(z)z^128 +l(z)≡h(z)r(z) + l(z). That is, we560* simply multiply the higher part of the operand by r(z) and add it to l(z). If561* the result is still larger than 128 bits, we reduce again.562*/563static inline uint8x16_t poly_mult_reduce(uint8x16x3_t input)564{565uint8x16_t const ZERO = vdupq_n_u8(0);566567uint64x2_t r = vreinterpretq_u64_u8(vdupq_n_u8(0x87));568#if defined(__GNUC__)569/* use 'asm' as an optimisation barrier to prevent loading MODULO from570* memory. It is for GNUC compatible compilers.571*/572asm volatile ("" : "+w" (r));573#endif574uint8x16_t const MODULO = vreinterpretq_u8_u64(vshrq_n_u64(r, 64 - 8));575uint8x16_t h, m, l; /* input high/middle/low 128b */576uint8x16_t c, d, e, f, g, n, o;577h = input.val[0]; /* h3:h2:00:00 */578m = input.val[1]; /* :m2:m1:00 */579l = input.val[2]; /* : :l1:l0 */580c = pmull_high(h, MODULO); /* :c2:c1:00 = reduction of h3 */581d = pmull_low(h, MODULO); /* : :d1:d0 = reduction of h2 */582e = veorq_u8(c, m); /* :e2:e1:00 = m2:m1:00 + c2:c1:00 */583f = pmull_high(e, MODULO); /* : :f1:f0 = reduction of e2 */584g = vextq_u8(ZERO, e, 8); /* : :g1:00 = e1:00 */585n = veorq_u8(d, l); /* : :n1:n0 = d1:d0 + l1:l0 */586o = veorq_u8(n, f); /* o1:o0 = f1:f0 + n1:n0 */587return veorq_u8(o, g); /* = o1:o0 + g1:00 */588}589590/*591* GCM multiplication: c = a times b in GF(2^128)592*/593void mbedtls_aesce_gcm_mult(unsigned char c[16],594const unsigned char a[16],595const unsigned char b[16])596{597uint8x16_t va, vb, vc;598va = vrbitq_u8(vld1q_u8(&a[0]));599vb = vrbitq_u8(vld1q_u8(&b[0]));600vc = vrbitq_u8(poly_mult_reduce(poly_mult_128(va, vb)));601vst1q_u8(&c[0], vc);602}603604#endif /* MBEDTLS_GCM_C */605606#if defined(MBEDTLS_POP_TARGET_PRAGMA)607#if defined(__clang__)608#pragma clang attribute pop609#elif defined(__GNUC__)610#pragma GCC pop_options611#endif612#undef MBEDTLS_POP_TARGET_PRAGMA613#endif614615#endif /* MBEDTLS_AESCE_HAVE_CODE */616617#endif /* MBEDTLS_AESCE_C */618619620