iPXE
aes.c
Go to the documentation of this file.
1/*
2 * Copyright (C) 2015 Michael Brown <mbrown@fensystems.co.uk>.
3 *
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public License as
6 * published by the Free Software Foundation; either version 2 of the
7 * License, or any later version.
8 *
9 * This program is distributed in the hope that it will be useful, but
10 * WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
17 * 02110-1301, USA.
18 *
19 * You can also choose to distribute this program under the terms of
20 * the Unmodified Binary Distribution Licence (as given in the file
21 * COPYING.UBDL), provided that you have satisfied its requirements.
22 */
23
24FILE_LICENCE ( GPL2_OR_LATER_OR_UBDL );
25FILE_SECBOOT ( PERMITTED );
26
27/** @file
28 *
29 * AES algorithm
30 *
31 */
32
33#include <stdint.h>
34#include <string.h>
35#include <errno.h>
36#include <assert.h>
37#include <byteswap.h>
38#include <ipxe/rotate.h>
39#include <ipxe/crypto.h>
40#include <ipxe/ecb.h>
41#include <ipxe/cbc.h>
42#include <ipxe/gcm.h>
43#include <ipxe/aes.h>
44
45/** AES strides
46 *
47 * These are the strides (modulo 16) used to walk through the AES
48 * input state bytes in order of byte position after [Inv]ShiftRows.
49 */
51 /** Input stride for ShiftRows
52 *
53 * 0 4 8 c
54 * \ \ \
55 * 1 5 9 d
56 * \ \ \
57 * 2 6 a e
58 * \ \ \
59 * 3 7 b f
60 */
62 /** Input stride for InvShiftRows
63 *
64 * 0 4 8 c
65 * / / /
66 * 1 5 9 d
67 * / / /
68 * 2 6 a e
69 * / / /
70 * 3 7 b f
71 */
73};
74
75/** A single AES lookup table entry
76 *
77 * This represents the product (in the Galois field GF(2^8)) of an
78 * eight-byte vector multiplier with a single scalar multiplicand.
79 *
80 * The vector multipliers used for AES will be {1,1,1,3,2,1,1,3} for
81 * MixColumns and {1,9,13,11,14,9,13,11} for InvMixColumns. This
82 * allows for the result of multiplying any single column of the
83 * [Inv]MixColumns matrix by a scalar value to be obtained simply by
84 * extracting the relevant four-byte subset from the lookup table
85 * entry.
86 *
87 * For example, to find the result of multiplying the second column of
88 * the MixColumns matrix by the scalar value 0x80:
89 *
90 * MixColumns column[0]: { 2, 1, 1, 3 }
91 * MixColumns column[1]: { 3, 2, 1, 1 }
92 * MixColumns column[2]: { 1, 3, 2, 1 }
93 * MixColumns column[3]: { 1, 1, 3, 2 }
94 * Vector multiplier: { 1, 1, 1, 3, 2, 1, 1, 3 }
95 * Scalar multiplicand: 0x80
96 * Lookup table entry: { 0x80, 0x80, 0x80, 0x9b, 0x1b, 0x80, 0x80, 0x9b }
97 *
98 * The second column of the MixColumns matrix is {3,2,1,1}. The
99 * product of this column with the scalar value 0x80 can be obtained
100 * by extracting the relevant four-byte subset of the lookup table
101 * entry:
102 *
103 * MixColumns column[1]: { 3, 2, 1, 1 }
104 * Vector multiplier: { 1, 1, 1, 3, 2, 1, 1, 3 }
105 * Lookup table entry: { 0x80, 0x80, 0x80, 0x9b, 0x1b, 0x80, 0x80, 0x9b }
106 * Product: { 0x9b, 0x1b, 0x80, 0x80 }
107 *
108 * The column lookups require only seven bytes of the eight-byte
109 * entry: the remaining (first) byte is used to hold the scalar
110 * multiplicand itself (i.e. the first byte of the vector multiplier
111 * is always chosen to be 1).
112 */
114 /** Viewed as an array of bytes */
115 uint8_t byte[8];
116} __attribute__ (( packed ));
117
118/** An AES lookup table
119 *
120 * This represents the products (in the Galois field GF(2^8)) of a
121 * constant eight-byte vector multiplier with all possible 256 scalar
122 * multiplicands.
123 *
124 * The entries are indexed by the AES [Inv]SubBytes S-box output
125 * values (denoted S(N)). This allows for the result of multiplying
126 * any single column of the [Inv]MixColumns matrix by S(N) to be
127 * obtained simply by extracting the relevant four-byte subset from
128 * the Nth table entry. For example:
129 *
130 * Input byte (N): 0x3a
131 * SubBytes output S(N): 0x80
132 * MixColumns column[1]: { 3, 2, 1, 1 }
133 * Vector multiplier: { 1, 1, 1, 3, 2, 1, 1, 3 }
134 * Table entry[0x3a]: { 0x80, 0x80, 0x80, 0x9b, 0x1b, 0x80, 0x80, 0x9b }
135 * Product: { 0x9b, 0x1b, 0x80, 0x80 }
136 *
137 * Since the first byte of the eight-byte vector multiplier is always
138 * chosen to be 1, the value of S(N) may be lookup up by extracting
139 * the first byte of the Nth table entry.
140 */
141struct aes_table {
142 /** Table entries, indexed by S(N) */
144} __attribute__ (( aligned ( 8 ) ));
145
146/** AES MixColumns lookup table */
148
149/** AES InvMixColumns lookup table */
151
152/** AES hardware acceleration mode has been selected */
153static int aes_selected;
154
155/**
156 * Multiply [Inv]MixColumns matrix column by scalar multiplicand
157 *
158 * @v entry AES lookup table entry for scalar multiplicand
159 * @v column [Inv]MixColumns matrix column index
160 * @ret product Product of matrix column with scalar multiplicand
161 */
162static inline __attribute__ (( always_inline )) uint32_t
163aes_entry_column ( const union aes_table_entry *entry, unsigned int column ) {
164 const union {
166 uint32_t column;
167 } __attribute__ (( may_alias )) *product;
168
169 /* Locate relevant four-byte subset */
170 product = container_of ( &entry->byte[ 4 - column ],
171 typeof ( *product ), byte );
172
173 /* Extract this four-byte subset */
174 return product->column;
175}
176
177/**
178 * Multiply [Inv]MixColumns matrix column by S-boxed input byte
179 *
180 * @v table AES lookup table
181 * @v stride AES row shift stride
182 * @v in AES input state
183 * @v offset Output byte offset (after [Inv]ShiftRows)
184 * @ret product Product of matrix column with S(input byte)
185 *
186 * Note that the specified offset is not the offset of the input byte;
187 * it is the offset of the output byte which corresponds to the input
188 * byte. This output byte offset is used to calculate both the input
189 * byte offset and to select the appropriate matric column.
190 *
191 * With a compile-time constant offset, this function will optimise
192 * down to a single "movzbl" (to extract the input byte) and will
193 * generate a single x86 memory reference expression which can then be
194 * used directly within a single "xorl" instruction.
195 */
196static inline __attribute__ (( always_inline )) uint32_t
197aes_column ( const struct aes_table *table, size_t stride,
198 const union aes_matrix *in, size_t offset ) {
199 const union aes_table_entry *entry;
200 unsigned int byte;
201
202 /* Extract input byte corresponding to this output byte offset
203 * (i.e. perform [Inv]ShiftRows).
204 */
205 byte = in->byte[ ( stride * offset ) & 0xf ];
206
207 /* Locate lookup table entry for this input byte (i.e. perform
208 * [Inv]SubBytes).
209 */
210 entry = &table->entry[byte];
211
212 /* Multiply appropriate matrix column by this input byte
213 * (i.e. perform [Inv]MixColumns).
214 */
215 return aes_entry_column ( entry, ( offset & 0x3 ) );
216}
217
218/**
219 * Calculate intermediate round output column
220 *
221 * @v table AES lookup table
222 * @v stride AES row shift stride
223 * @v in AES input state
224 * @v key AES round key
225 * @v column Column index
226 * @ret output Output column value
227 */
228static inline __attribute__ (( always_inline )) uint32_t
229aes_output ( const struct aes_table *table, size_t stride,
230 const union aes_matrix *in, const union aes_matrix *key,
231 unsigned int column ) {
232 size_t offset = ( column * 4 );
233
234 /* Perform [Inv]ShiftRows, [Inv]SubBytes, [Inv]MixColumns, and
235 * AddRoundKey for this column. The loop is unrolled to allow
236 * for the required compile-time constant optimisations.
237 */
238 return ( aes_column ( table, stride, in, ( offset + 0 ) ) ^
239 aes_column ( table, stride, in, ( offset + 1 ) ) ^
240 aes_column ( table, stride, in, ( offset + 2 ) ) ^
241 aes_column ( table, stride, in, ( offset + 3 ) ) ^
242 key->column[column] );
243}
244
245/**
246 * Perform a single intermediate round
247 *
248 * @v table AES lookup table
249 * @v stride AES row shift stride
250 * @v in AES input state
251 * @v out AES output state
252 * @v key AES round key
253 */
254static inline __attribute__ (( always_inline )) void
255aes_round ( const struct aes_table *table, size_t stride,
256 const union aes_matrix *in, union aes_matrix *out,
257 const union aes_matrix *key ) {
258
259 /* Perform [Inv]ShiftRows, [Inv]SubBytes, [Inv]MixColumns, and
260 * AddRoundKey for all columns. The loop is unrolled to allow
261 * for the required compile-time constant optimisations.
262 */
263 out->column[0] = aes_output ( table, stride, in, key, 0 );
264 out->column[1] = aes_output ( table, stride, in, key, 1 );
265 out->column[2] = aes_output ( table, stride, in, key, 2 );
266 out->column[3] = aes_output ( table, stride, in, key, 3 );
267}
268
269/**
270 * Perform encryption intermediate rounds
271 *
272 * @v in AES input state
273 * @v out AES output state
274 * @v key Round keys
275 * @v rounds Number of intermediate rounds (must be odd)
276 * @ret key Final round key
277 *
278 * This function is deliberately marked as non-inlinable to ensure
279 * maximal availability of registers for GCC's register allocator,
280 * which has a tendency to otherwise spill performance-critical
281 * registers to the stack.
282 */
283static __attribute__ (( noinline )) const union aes_matrix *
285 const union aes_matrix *key, unsigned int rounds ) {
286 union aes_matrix *tmp;
287
288 /* Perform intermediate rounds */
289 do {
290 /* Perform one intermediate round */
292 in, out, key++ );
293
294 /* Swap input and output states for next round */
295 tmp = in;
296 in = out;
297 out = tmp;
298
299 } while ( --rounds );
300
301 return key;
302}
303
304/**
305 * Perform decryption intermediate rounds
306 *
307 * @v in AES input state
308 * @v out AES output state
309 * @v key Round keys
310 * @v rounds Number of intermediate rounds (must be odd)
311 * @ret key Final round key
312 *
313 * As with aes_encrypt_rounds(), this function is deliberately marked
314 * as non-inlinable.
315 *
316 * This function could potentially use the same binary code as is used
317 * for encryption. To compensate for the difference between ShiftRows
318 * and InvShiftRows, half of the input byte offsets would have to be
319 * modifiable at runtime (half by an offset of +4/-4, half by an
320 * offset of -4/+4 for ShiftRows/InvShiftRows). This can be
321 * accomplished in x86 assembly within the number of available
322 * registers, but GCC's register allocator struggles to do so,
323 * resulting in a significant performance decrease due to registers
324 * being spilled to the stack. We therefore use two separate but very
325 * similar binary functions based on the same C source.
326 */
327static __attribute__ (( noinline )) const union aes_matrix *
329 const union aes_matrix *key, unsigned int rounds ) {
330 union aes_matrix *tmp;
331
332 /* Perform intermediate rounds */
333 do {
334 /* Perform one intermediate round */
336 in, out, key++ );
337
338 /* Swap input and output states for next round */
339 tmp = in;
340 in = out;
341 out = tmp;
342
343 } while ( --rounds );
344
345 return key;
346}
347
348/**
349 * Perform standalone AddRoundKey
350 *
351 * @v state AES state
352 * @v key AES round key
353 */
354static inline __attribute__ (( always_inline )) void
356
357 state->column[0] ^= key->column[0];
358 state->column[1] ^= key->column[1];
359 state->column[2] ^= key->column[2];
360 state->column[3] ^= key->column[3];
361}
362
363/**
364 * Perform final round
365 *
366 * @v table AES lookup table
367 * @v stride AES row shift stride
368 * @v in AES input state
369 * @v out AES output state
370 * @v key AES round key
371 */
372static void aes_final ( const struct aes_table *table, size_t stride,
373 const union aes_matrix *in, union aes_matrix *out,
374 const union aes_matrix *key ) {
375 const union aes_table_entry *entry;
376 unsigned int byte;
377 size_t out_offset;
378 size_t in_offset;
379
380 /* Perform [Inv]ShiftRows and [Inv]SubBytes */
381 for ( out_offset = 0, in_offset = 0 ; out_offset < 16 ;
382 out_offset++, in_offset = ( ( in_offset + stride ) & 0xf ) ) {
383
384 /* Extract input byte (i.e. perform [Inv]ShiftRows) */
385 byte = in->byte[in_offset];
386
387 /* Locate lookup table entry for this input byte
388 * (i.e. perform [Inv]SubBytes).
389 */
390 entry = &table->entry[byte];
391
392 /* Store output byte */
393 out->byte[out_offset] = entry->byte[0];
394 }
395
396 /* Perform AddRoundKey */
398}
399
400/**
401 * Calculate number of intermediate rounds
402 *
403 * @v aes AES context
404 * @ret rounds Number of intermediate rounds (must be odd)
405 */
406static unsigned int aes_rounds ( const struct aes_context *aes ) {
407 unsigned int rounds;
408
409 /* Ensure that the number of intermediate rounds is a safe
410 * value even on a completely uninitialized context.
411 */
412 rounds = ( ( aes->rounds & 6 ) + 7 );
413 assert ( rounds <= ( AES_MAX_ROUNDS - 2 ) );
414 assert ( rounds & 1 );
415 return rounds;
416}
417
418/**
419 * Encrypt data
420 *
421 * @v cipher Cipher algorithm
422 * @v ctx Context
423 * @v src Data to encrypt
424 * @v dst Buffer for encrypted data
425 * @v len Length of data
426 */
427static void aes_encrypt ( struct cipher_algorithm *cipher __unused, void *ctx,
428 const void *src, void *dst, size_t len ) {
429 const struct aes_context *aes = aes_context ( ctx );
430 const union aes_matrix *key = aes->encrypt.key;
431 union aes_matrix buffer[2];
432 union aes_matrix *in = &buffer[0];
433 union aes_matrix *out = &buffer[1];
434
435 /* Sanity check */
436 assert ( len == sizeof ( *in ) );
437
438 /* Initialise input state */
439 memcpy ( in, src, sizeof ( *in ) );
440
441 /* Perform initial round (AddRoundKey) */
442 aes_addroundkey ( in, key++ );
443
444 /* Perform intermediate rounds (ShiftRows, SubBytes,
445 * MixColumns, AddRoundKey).
446 */
447 key = aes_encrypt_rounds ( in, out, key, aes_rounds ( aes ) );
448 in = out;
449
450 /* Perform final round (ShiftRows, SubBytes, AddRoundKey) */
451 out = dst;
453}
454
455/**
456 * Decrypt data
457 *
458 * @v cipher Cipher algorithm
459 * @v ctx Context
460 * @v src Data to decrypt
461 * @v dst Buffer for decrypted data
462 * @v len Length of data
463 */
464static void aes_decrypt ( struct cipher_algorithm *cipher __unused, void *ctx,
465 const void *src, void *dst, size_t len ) {
466 const struct aes_context *aes = aes_context ( ctx );
467 const union aes_matrix *key = aes->decrypt.key;
468 union aes_matrix buffer[2];
469 union aes_matrix *in = &buffer[0];
470 union aes_matrix *out = &buffer[1];
471
472 /* Sanity check */
473 assert ( len == sizeof ( *in ) );
474
475 /* Initialise input state */
476 memcpy ( in, src, sizeof ( *in ) );
477
478 /* Perform initial round (AddRoundKey) */
479 aes_addroundkey ( in, key++ );
480
481 /* Perform intermediate rounds (InvShiftRows, InvSubBytes,
482 * InvMixColumns, AddRoundKey).
483 */
484 key = aes_decrypt_rounds ( in, out, key, aes_rounds ( aes ) );
485 in = out;
486
487 /* Perform final round (InvShiftRows, InvSubBytes, AddRoundKey) */
488 out = dst;
490}
491
492/**
493 * Multiply a polynomial by (x) modulo (x^8 + x^4 + x^3 + x^2 + 1) in GF(2^8)
494 *
495 * @v poly Polynomial to be multiplied
496 * @ret result Result
497 */
498static __attribute__ (( const )) unsigned int aes_double ( unsigned int poly ) {
499
500 /* Multiply polynomial by (x), placing the resulting x^8
501 * coefficient in the LSB (i.e. rotate byte left by one).
502 */
503 poly = rol8 ( poly, 1 );
504
505 /* If coefficient of x^8 (in LSB) is non-zero, then reduce by
506 * subtracting (x^8 + x^4 + x^3 + x^2 + 1) in GF(2^8).
507 */
508 if ( poly & 0x01 ) {
509 poly ^= 0x01; /* Subtract x^8 (currently in LSB) */
510 poly ^= 0x1b; /* Subtract (x^4 + x^3 + x^2 + 1) */
511 }
512
513 return poly;
514}
515
516/**
517 * Fill in MixColumns lookup table entry
518 *
519 * @v entry AES lookup table entry for scalar multiplicand
520 *
521 * The MixColumns lookup table vector multiplier is {1,1,1,3,2,1,1,3}.
522 */
523static void aes_mixcolumns_entry ( union aes_table_entry *entry ) {
524 unsigned int scalar_x_1;
525 unsigned int scalar_x;
526 unsigned int scalar;
527
528 /* Retrieve scalar multiplicand */
529 scalar = entry->byte[0];
530 entry->byte[1] = scalar;
531 entry->byte[2] = scalar;
532 entry->byte[5] = scalar;
533 entry->byte[6] = scalar;
534
535 /* Calculate scalar multiplied by (x) */
536 scalar_x = aes_double ( scalar );
537 entry->byte[4] = scalar_x;
538
539 /* Calculate scalar multiplied by (x + 1) */
540 scalar_x_1 = ( scalar_x ^ scalar );
541 entry->byte[3] = scalar_x_1;
542 entry->byte[7] = scalar_x_1;
543}
544
545/**
546 * Fill in InvMixColumns lookup table entry
547 *
548 * @v entry AES lookup table entry for scalar multiplicand
549 *
550 * The InvMixColumns lookup table vector multiplier is {1,9,13,11,14,9,13,11}.
551 */
552static void aes_invmixcolumns_entry ( union aes_table_entry *entry ) {
553 unsigned int scalar_x3_x2_x;
554 unsigned int scalar_x3_x2_1;
555 unsigned int scalar_x3_x2;
556 unsigned int scalar_x3_x_1;
557 unsigned int scalar_x3_1;
558 unsigned int scalar_x3;
559 unsigned int scalar_x2;
560 unsigned int scalar_x;
561 unsigned int scalar;
562
563 /* Retrieve scalar multiplicand */
564 scalar = entry->byte[0];
565
566 /* Calculate scalar multiplied by (x) */
567 scalar_x = aes_double ( scalar );
568
569 /* Calculate scalar multiplied by (x^2) */
570 scalar_x2 = aes_double ( scalar_x );
571
572 /* Calculate scalar multiplied by (x^3) */
573 scalar_x3 = aes_double ( scalar_x2 );
574
575 /* Calculate scalar multiplied by (x^3 + 1) */
576 scalar_x3_1 = ( scalar_x3 ^ scalar );
577 entry->byte[1] = scalar_x3_1;
578 entry->byte[5] = scalar_x3_1;
579
580 /* Calculate scalar multiplied by (x^3 + x + 1) */
581 scalar_x3_x_1 = ( scalar_x3_1 ^ scalar_x );
582 entry->byte[3] = scalar_x3_x_1;
583 entry->byte[7] = scalar_x3_x_1;
584
585 /* Calculate scalar multiplied by (x^3 + x^2) */
586 scalar_x3_x2 = ( scalar_x3 ^ scalar_x2 );
587
588 /* Calculate scalar multiplied by (x^3 + x^2 + 1) */
589 scalar_x3_x2_1 = ( scalar_x3_x2 ^ scalar );
590 entry->byte[2] = scalar_x3_x2_1;
591 entry->byte[6] = scalar_x3_x2_1;
592
593 /* Calculate scalar multiplied by (x^3 + x^2 + x) */
594 scalar_x3_x2_x = ( scalar_x3_x2 ^ scalar_x );
595 entry->byte[4] = scalar_x3_x2_x;
596}
597
598/**
599 * Generate AES lookup tables
600 *
601 */
602static void aes_generate ( void ) {
603 union aes_table_entry *entry;
604 union aes_table_entry *inventry;
605 unsigned int poly = 0x01;
606 unsigned int invpoly = 0x01;
607 unsigned int transformed;
608 unsigned int i;
609
610 /* Iterate over non-zero values of GF(2^8) using generator (x + 1) */
611 do {
612
613 /* Multiply polynomial by (x + 1) */
614 poly ^= aes_double ( poly );
615
616 /* Divide inverse polynomial by (x + 1). This code
617 * fragment is taken directly from the Wikipedia page
618 * on the Rijndael S-box. An explanation of why it
619 * works would be greatly appreciated.
620 */
621 invpoly ^= ( invpoly << 1 );
622 invpoly ^= ( invpoly << 2 );
623 invpoly ^= ( invpoly << 4 );
624 if ( invpoly & 0x80 )
625 invpoly ^= 0x09;
626 invpoly &= 0xff;
627
628 /* Apply affine transformation */
629 transformed = ( 0x63 ^ invpoly ^ rol8 ( invpoly, 1 ) ^
630 rol8 ( invpoly, 2 ) ^ rol8 ( invpoly, 3 ) ^
631 rol8 ( invpoly, 4 ) );
632
633 /* Populate S-box (within MixColumns lookup table) */
634 aes_mixcolumns.entry[poly].byte[0] = transformed;
635
636 } while ( poly != 0x01 );
637
638 /* Populate zeroth S-box entry (which has no inverse) */
639 aes_mixcolumns.entry[0].byte[0] = 0x63;
640
641 /* Fill in MixColumns and InvMixColumns lookup tables */
642 for ( i = 0 ; i < 256 ; i++ ) {
643
644 /* Fill in MixColumns lookup table entry */
645 entry = &aes_mixcolumns.entry[i];
646 aes_mixcolumns_entry ( entry );
647
648 /* Populate inverse S-box (within InvMixColumns lookup table) */
649 inventry = &aes_invmixcolumns.entry[ entry->byte[0] ];
650 inventry->byte[0] = i;
651
652 /* Fill in InvMixColumns lookup table entry */
653 aes_invmixcolumns_entry ( inventry );
654 }
655}
656
657/**
658 * Rotate key column
659 *
660 * @v column Key column
661 * @ret column Updated key column
662 */
663static inline __attribute__ (( always_inline )) uint32_t
665
666 return ( ( __BYTE_ORDER == __LITTLE_ENDIAN ) ?
667 ror32 ( column, 8 ) : rol32 ( column, 8 ) );
668}
669
670/**
671 * Apply S-box to key column
672 *
673 * @v column Key column
674 * @ret column Updated key column
675 */
676static uint32_t aes_key_sbox ( uint32_t column ) {
677 unsigned int i;
679
680 for ( i = 0 ; i < 4 ; i++ ) {
681 byte = ( column & 0xff );
682 byte = aes_mixcolumns.entry[byte].byte[0];
683 column = ( ( column & ~0xff ) | byte );
684 column = rol32 ( column, 8 );
685 }
686 return column;
687}
688
689/**
690 * Apply schedule round constant to key column
691 *
692 * @v column Key column
693 * @v rcon Round constant
694 * @ret column Updated key column
695 */
696static inline __attribute__ (( always_inline )) uint32_t
697aes_key_rcon ( uint32_t column, unsigned int rcon ) {
698
699 return ( ( __BYTE_ORDER == __LITTLE_ENDIAN ) ?
700 ( column ^ rcon ) : ( column ^ ( rcon << 24 ) ) );
701}
702
703/**
704 * Set key
705 *
706 * @v cipher Cipher algorithm
707 * @v ctx Context
708 * @v key Key
709 * @v keylen Key length
710 * @ret rc Return status code
711 */
712static int aes_setkey ( struct cipher_algorithm *cipher __unused, void *ctx,
713 const void *key, size_t keylen ) {
714 struct aes_context *aes = aes_context ( ctx );
715 union aes_matrix *enc;
716 union aes_matrix *dec;
717 union aes_matrix temp;
718 union aes_matrix zero;
719 unsigned int rcon = 0x01;
720 unsigned int rounds;
721 size_t offset = 0;
722 uint32_t *prev;
723 uint32_t *next;
724 uint32_t *end;
726
727 /* Attempt (once) to enable AES hardware acceleration */
728 if ( ! aes_selected ) {
730 aes_selected = 1;
731 }
732
733 /* Generate lookup tables, if not already done */
734 if ( ! aes_mixcolumns.entry[0].byte[0] )
735 aes_generate();
736
737 /* Validate key length and calculate number of intermediate rounds */
738 switch ( keylen ) {
739 case ( 128 / 8 ) :
740 rounds = 11;
741 break;
742 case ( 192 / 8 ) :
743 rounds = 13;
744 break;
745 case ( 256 / 8 ) :
746 rounds = 15;
747 break;
748 default:
749 DBGC ( aes, "AES %p unsupported key length (%zd bits)\n",
750 aes, ( keylen * 8 ) );
751 return -EINVAL;
752 }
753 aes->rounds = rounds;
754 enc = aes->encrypt.key;
755 end = enc[rounds].column;
756
757 /* Copy raw key */
758 memcpy ( enc, key, keylen );
759 prev = enc->column;
760 next = ( ( ( void * ) prev ) + keylen );
761 tmp = next[-1];
762
763 /* Construct expanded key */
764 while ( next < end ) {
765
766 /* If this is the first column of an expanded key
767 * block, or the middle column of an AES-256 key
768 * block, then apply the S-box.
769 */
770 if ( ( offset == 0 ) || ( ( offset | keylen ) == 48 ) )
771 tmp = aes_key_sbox ( tmp );
772
773 /* If this is the first column of an expanded key
774 * block then rotate and apply the round constant.
775 */
776 if ( offset == 0 ) {
777 tmp = aes_key_rotate ( tmp );
778 tmp = aes_key_rcon ( tmp, rcon );
779 rcon = aes_double ( rcon );
780 }
781
782 /* XOR with previous key column */
783 tmp ^= *prev;
784
785 /* Store column */
786 *next = tmp;
787
788 /* Move to next column */
789 offset += sizeof ( *next );
790 if ( offset == keylen )
791 offset = 0;
792 next++;
793 prev++;
794 }
795 DBGC2 ( aes, "AES %p expanded %zd-bit key:\n", aes, ( keylen * 8 ) );
796 DBGC2_HDA ( aes, 0, &aes->encrypt, ( rounds * sizeof ( *enc ) ) );
797
798 /* Convert to decryption key */
799 memset ( &zero, 0, sizeof ( zero ) );
800 dec = &aes->decrypt.key[ rounds - 1 ];
801 memcpy ( dec--, enc++, sizeof ( *dec ) );
802 while ( dec > aes->decrypt.key ) {
803 /* Perform InvMixColumns (by reusing the encryption
804 * final-round code to perform ShiftRows+SubBytes and
805 * reusing the decryption intermediate-round code to
806 * perform InvShiftRows+InvSubBytes+InvMixColumns, all
807 * with a zero encryption key).
808 */
810 enc++, &temp, &zero );
811 aes_decrypt_rounds ( &temp, dec--, &zero, 1 );
812 }
813 memcpy ( dec--, enc++, sizeof ( *dec ) );
814 DBGC2 ( aes, "AES %p inverted %zd-bit key:\n", aes, ( keylen * 8 ) );
815 DBGC2_HDA ( aes, 0, &aes->decrypt, ( rounds * sizeof ( *dec ) ) );
816
817 return 0;
818}
819
820/**
821 * Disable hardware acceleration (for testing)
822 *
823 */
824void aes_decelerate ( void ) {
825
826 /* Restore original algorithm pointers */
827 aes_algorithm.encrypt = aes_encrypt;
828 aes_algorithm.decrypt = aes_decrypt;
829 DBGC ( &aes_algorithm, "AES disabled hardware acceleration\n" );
830
831 /* Mark hardware acceleration mode as selected */
832 aes_selected = 1;
833}
834
835/**
836 * Check if hardware acceleration is currently enabled (for testing)
837 *
838 * @ret is_accelerated AES is using hardware acceleration
839 */
840int aes_is_accelerated ( void ) {
841
842 /* Check if hardware acceleration is enabled */
843 return ( aes_algorithm.encrypt != aes_encrypt );
844}
845
846/** Basic AES algorithm */
848 .name = "aes",
849 .ctxsize = sizeof ( struct aes_context ),
850 .blocksize = AES_BLOCKSIZE,
851 .alignsize = 0,
852 .authsize = 0,
853 .confidential = 1,
854 .setkey = aes_setkey,
855 .setiv = cipher_null_setiv,
856 .encrypt = aes_encrypt,
857 .decrypt = aes_decrypt,
858 .auth = cipher_null_auth,
859};
860
861/* AES in Electronic Codebook mode */
864
865/* AES in Cipher Block Chaining mode */
868
869/* AES in Galois/Counter mode */
struct golan_eq_context ctx
Definition CIB_PRM.h:0
__be32 out[4]
Definition CIB_PRM.h:8
__be32 in[4]
Definition CIB_PRM.h:7
union @162305117151260234136356364136041353210355154177 key
typeof(acpi_finder=acpi_find)
ACPI table finder.
Definition acpi.c:48
static uint32_t aes_key_sbox(uint32_t column)
Apply S-box to key column.
Definition aes.c:676
static struct aes_table aes_mixcolumns
AES MixColumns lookup table.
Definition aes.c:147
struct cipher_algorithm aes_algorithm
Basic AES algorithm.
Definition aes.c:847
static void aes_round(const struct aes_table *table, size_t stride, const union aes_matrix *in, union aes_matrix *out, const union aes_matrix *key)
Perform a single intermediate round.
Definition aes.c:255
static void aes_generate(void)
Generate AES lookup tables.
Definition aes.c:602
aes_stride
AES strides.
Definition aes.c:50
@ AES_STRIDE_SHIFTROWS
Input stride for ShiftRows.
Definition aes.c:61
@ AES_STRIDE_INVSHIFTROWS
Input stride for InvShiftRows.
Definition aes.c:72
int aes_is_accelerated(void)
Check if hardware acceleration is currently enabled (for testing).
Definition aes.c:840
static void aes_final(const struct aes_table *table, size_t stride, const union aes_matrix *in, union aes_matrix *out, const union aes_matrix *key)
Perform final round.
Definition aes.c:372
static void aes_addroundkey(union aes_matrix *state, const union aes_matrix *key)
Perform standalone AddRoundKey.
Definition aes.c:355
static uint32_t aes_key_rcon(uint32_t column, unsigned int rcon)
Apply schedule round constant to key column.
Definition aes.c:697
static void aes_encrypt(struct cipher_algorithm *cipher __unused, void *ctx, const void *src, void *dst, size_t len)
Encrypt data.
Definition aes.c:427
static void aes_decrypt(struct cipher_algorithm *cipher __unused, void *ctx, const void *src, void *dst, size_t len)
Decrypt data.
Definition aes.c:464
static uint32_t aes_entry_column(const union aes_table_entry *entry, unsigned int column)
Multiply [Inv]MixColumns matrix column by scalar multiplicand.
Definition aes.c:163
static uint32_t aes_output(const struct aes_table *table, size_t stride, const union aes_matrix *in, const union aes_matrix *key, unsigned int column)
Calculate intermediate round output column.
Definition aes.c:229
void aes_decelerate(void)
Disable hardware acceleration (for testing).
Definition aes.c:824
static unsigned int aes_rounds(const struct aes_context *aes)
Calculate number of intermediate rounds.
Definition aes.c:406
static unsigned int aes_double(unsigned int poly)
Multiply a polynomial by (x) modulo (x^8 + x^4 + x^3 + x^2 + 1) in GF(2^8).
Definition aes.c:498
static int aes_setkey(struct cipher_algorithm *cipher __unused, void *ctx, const void *key, size_t keylen)
Set key.
Definition aes.c:712
static uint32_t aes_column(const struct aes_table *table, size_t stride, const union aes_matrix *in, size_t offset)
Multiply [Inv]MixColumns matrix column by S-boxed input byte.
Definition aes.c:197
static const union aes_matrix * aes_encrypt_rounds(union aes_matrix *in, union aes_matrix *out, const union aes_matrix *key, unsigned int rounds)
Perform encryption intermediate rounds.
Definition aes.c:284
static void aes_mixcolumns_entry(union aes_table_entry *entry)
Fill in MixColumns lookup table entry.
Definition aes.c:523
static struct aes_table aes_invmixcolumns
AES InvMixColumns lookup table.
Definition aes.c:150
static void aes_invmixcolumns_entry(union aes_table_entry *entry)
Fill in InvMixColumns lookup table entry.
Definition aes.c:552
static int aes_selected
AES hardware acceleration mode has been selected.
Definition aes.c:153
static const union aes_matrix * aes_decrypt_rounds(union aes_matrix *in, union aes_matrix *out, const union aes_matrix *key, unsigned int rounds)
Perform decryption intermediate rounds.
Definition aes.c:328
static uint32_t aes_key_rotate(uint32_t column)
Rotate key column.
Definition aes.c:664
void aes_accelerate(void)
Enable hardware acceleration (if supported).
Definition aesni.c:211
unsigned int uint32_t
Definition stdint.h:12
unsigned char uint8_t
Definition stdint.h:10
#define __BYTE_ORDER
Definition endian.h:7
static const void * src
Definition string.h:48
Assertions.
#define assert(condition)
Assert a condition at run-time.
Definition assert.h:61
uint16_t offset
Offset to command line.
Definition bzimage.h:3
Cipher-block chaining.
#define CBC_CIPHER(_cbc_name, _cbc_cipher, _raw_cipher, _raw_context, _blocksize)
Create a cipher-block chaining mode of behaviour of an existing cipher.
Definition cbc.h:40
int cipher_null_setiv(struct cipher_algorithm *cipher __unused, void *ctx __unused, const void *iv __unused, size_t ivlen __unused)
Definition crypto_null.c:70
void cipher_null_auth(struct cipher_algorithm *cipher __unused, void *ctx __unused, void *auth __unused)
Definition crypto_null.c:89
uint32_t next
Next descriptor address.
Definition dwmac.h:11
ring len
Length.
Definition dwmac.h:226
Electronic codebook (ECB).
#define ECB_CIPHER(_ecb_name, _ecb_cipher, _raw_cipher, _raw_context, _blocksize)
Create an electronic codebook mode of behaviour of an existing cipher.
Definition ecb.h:31
struct ena_llq_option stride
Descriptor strides.
Definition ena.h:11
Error codes.
uint8_t state
State.
Definition eth_slow.h:36
Galois/Counter Mode (GCM).
#define GCM_CIPHER(_gcm_name, _gcm_cipher, _raw_cipher, _raw_context, _blocksize)
Create a GCM mode of behaviour of an existing cipher.
Definition gcm.h:88
#define __unused
Declare a variable or data structure as unused.
Definition compiler.h:598
#define DBGC2(...)
Definition compiler.h:547
#define DBGC2_HDA(...)
Definition compiler.h:548
#define DBGC(...)
Definition compiler.h:530
uint32_t buffer
Buffer index (or NETVSC_RNDIS_NO_BUFFER).
Definition netvsc.h:5
#define FILE_LICENCE(_licence)
Declare a particular licence as applying to a file.
Definition compiler.h:921
#define EINVAL
Invalid argument.
Definition errno.h:472
#define FILE_SECBOOT(_status)
Declare a file's UEFI Secure Boot permission status.
Definition compiler.h:951
#define __attribute__(x)
Definition compiler.h:10
#define __LITTLE_ENDIAN
Constant representing little-endian byte order.
Definition endian.h:13
AES algorithm.
#define AES_MAX_ROUNDS
Maximum number of AES rounds.
Definition aes.h:20
struct cipher_algorithm aes_ecb_algorithm
struct cipher_algorithm aes_cbc_algorithm
static struct aes_context * aes_context(void *ctx)
Align AES context.
Definition aes.h:55
struct cipher_algorithm aes_gcm_algorithm
#define AES_BLOCKSIZE
AES blocksize.
Definition aes.h:17
Cryptographic API.
uint8_t product
Product string.
Definition smbios.h:5
String functions.
void * memcpy(void *dest, const void *src, size_t len) __nonnull
void * memset(void *dest, int character, size_t len) __nonnull
unsigned long tmp
Definition linux_pci.h:65
uint32_t end
Ending offset.
Definition netvsc.h:7
Bit operations.
unsigned char byte
Definition smc9000.h:38
#define container_of(ptr, type, field)
Get containing structure.
Definition stddef.h:36
AES context.
Definition aes.h:37
struct aes_round_keys decrypt
Decryption keys.
Definition aes.h:41
uint8_t rounds
Number of rounds.
Definition aes.h:43
struct aes_round_keys encrypt
Encryption keys.
Definition aes.h:39
union aes_matrix key[AES_MAX_ROUNDS]
Round keys.
Definition aes.h:33
An AES lookup table.
Definition aes.c:141
union aes_table_entry entry[256]
Table entries, indexed by S(N).
Definition aes.c:143
A cipher algorithm.
Definition crypto.h:58
AES matrix.
Definition aes.h:23
uint32_t column[4]
Viewed as an array of four-byte columns.
Definition aes.h:27
A single AES lookup table entry.
Definition aes.c:113
uint8_t byte[8]
Viewed as an array of bytes.
Definition aes.c:115
static u32 ror32(u32 v, int bits)
Rotate 32-bit value right.
Definition wpa_tkip.c:162
static u32 rol32(u32 v, int bits)
Rotate 32-bit value left.
Definition wpa_tkip.c:174