block cipher modes of operation and cmac for authentication

26
Block Cipher Modes of Operation and the CMAC Mode for Authentication Alberto Grand December 20, 2007 Abstract A block cipher is a symmetric key cipher which operates on fixed- length groups of bits. Whenever the input plaintext exceeds the block size, a so called “mode of operation” must be employed along with the block cipher. A block cipher mode, or mode, for short, is an algo- rithm that features the use of a symmetric key block cipher algorithm to provide an information service, such as confidentiality or authenti- cation. The first part of this article aims at outlining five NIST recom- mended modes of operation which provide confidentiality (but do not ensure message integrity): Electronic Codebook (ECB), Cipher Block Chaining (CBC), Cipher Feedback (CFB), Output Feedback (OFB) and Counter (CTR). The second part of the article focuses on a mes- sage authentication code (MAC) algorithm based on a symmetric key block cipher, the CMAC algorithm. The CMAC authentication mode is also one of the seven modes which may be used with NIST’s ap- proved encryption algorithms. 1

Upload: project-symphony-collection

Post on 12-Nov-2014

2.166 views

Category:

Documents


0 download

DESCRIPTION

And this is the first homework of Alberto Grand for Computer System Security! As the abstract says, a block cipher is a symmetric key cipher which operates on fixed-length groups of bits. Whenever the input plaintext exceeds the block size, a so called “mode of operation” must be employed along with the block cipher. A block cipher mode, or mode, for short, is an algorithm that features the use of a symmetric key block cipher algorithm to provide an information service, such as confidentiality or authentication.

TRANSCRIPT

Page 1: Block Cipher Modes of Operation and CMAC for Authentication

Block Cipher Modes of Operationand

the CMAC Mode for Authentication

Alberto Grand

December 20, 2007

Abstract

A block cipher is a symmetric key cipher which operates on fixed-length groups of bits. Whenever the input plaintext exceeds the blocksize, a so called “mode of operation” must be employed along withthe block cipher. A block cipher mode, or mode, for short, is an algo-rithm that features the use of a symmetric key block cipher algorithmto provide an information service, such as confidentiality or authenti-cation. The first part of this article aims at outlining five NIST recom-mended modes of operation which provide confidentiality (but do notensure message integrity): Electronic Codebook (ECB), Cipher BlockChaining (CBC), Cipher Feedback (CFB), Output Feedback (OFB)and Counter (CTR). The second part of the article focuses on a mes-sage authentication code (MAC) algorithm based on a symmetric keyblock cipher, the CMAC algorithm. The CMAC authentication modeis also one of the seven modes which may be used with NIST’s ap-proved encryption algorithms.

1

Page 2: Block Cipher Modes of Operation and CMAC for Authentication

Contents

1 Cipher block modes of operation 31.1 Five confidentiality modes of operation . . . . . . . . . . . . . 3

1.1.1 Electronic Codebook (ECB) . . . . . . . . . . . . . . . 31.1.2 Cipher Block Chaining (CBC) . . . . . . . . . . . . . . 51.1.3 Cipher Feedback (CFB) . . . . . . . . . . . . . . . . . 71.1.4 Output Feedback (OFB) . . . . . . . . . . . . . . . . . 111.1.5 Counter (CTR) . . . . . . . . . . . . . . . . . . . . . . 12

1.2 Generation of Initialization Vectors . . . . . . . . . . . . . . . 151.3 Padding-related issues . . . . . . . . . . . . . . . . . . . . . . 15

1.3.1 Padding techniques . . . . . . . . . . . . . . . . . . . . 151.3.2 Ciphertext stealing (CTS) . . . . . . . . . . . . . . . . 16

1.4 Related-mode attacks . . . . . . . . . . . . . . . . . . . . . . . 181.4.1 Exploiting an ECB Oracle to attack the CTR mode . . 181.4.2 Exploiting a CBC Oracle to attack the CTR mode . . 18

2 The CMAC Mode for Authentication 192.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192.2 Cipher Block Chaining MAC (CBC-MAC) . . . . . . . . . . . 19

2.2.1 Description . . . . . . . . . . . . . . . . . . . . . . . . 202.2.2 Weaknesses . . . . . . . . . . . . . . . . . . . . . . . . 20

2.3 CMAC Specification . . . . . . . . . . . . . . . . . . . . . . . 212.3.1 Subkeys generation . . . . . . . . . . . . . . . . . . . . 212.3.2 CMAC generation . . . . . . . . . . . . . . . . . . . . . 222.3.3 CMAC verification . . . . . . . . . . . . . . . . . . . . 22

2.4 Security issues . . . . . . . . . . . . . . . . . . . . . . . . . . . 232.4.1 Length of the MAC . . . . . . . . . . . . . . . . . . . . 232.4.2 Message span of the key . . . . . . . . . . . . . . . . . 242.4.3 Protection against replay attacks . . . . . . . . . . . . 25

References 26

2

Page 3: Block Cipher Modes of Operation and CMAC for Authentication

1 Cipher block modes of operation

1.1 Five confidentiality modes of operation

1.1.1 Electronic Codebook (ECB)

The Electronic Codebook (ECB) is the simplest, and the most insecure, ofthe five modes of operation hereby described. Each input block is processedindependently of all others. The algorithm lies, for each and every block,in a permutation over the set of all input blocks. The term codebook isused because, for a given key, there is a unique ciphertext for every blockof plaintext. Therefore, we can imagine a gigantic codebook in which thereis an entry for every possible plaintext pattern showing its correspondingciphertext.

This mode of operation requires that the input plaintext size be a multipleof the block size; if this is not the case, padding must be added to the lastinput block. Padding techniques, along with possible drawbacks, will befurtherly discussed.

The mode of operation is defined as follows:

ECB encryption: Cj = CIPHk(Pj)

Figure 1: ECB encryption.

ECB decryption: Pj = CIPH−1k (Pj)

Every block being processed separately, both encryption and decryptioncan be carried out in parallel on different blocks; this is one of the few ad-vantages, if any, of the ECB mode of operation. Because of this peculiarityof the ECB mode, bit errors in a single ciphertext block only cause the cor-responding decrypted block to be incorrect and do not affect other blocks. A

3

Page 4: Block Cipher Modes of Operation and CMAC for Authentication

Figure 2: ECB decryption.

single bit error in a ciphertext block may produce an error in any bit posi-tion of the decrypted block, with an expected error rate of 50% (depending,however, on the underlying block cipher).

On the other hand, identical plaintext blocks always get encrypted intoidentical ciphertext blocks. This is a serious weakness of the ECB mode ofoperation, because it results in data patterns being scarcely hidden. To someextent, message confidentiality is even compromised. An example of howineffectively data patterns in the plaintext are handled is given in Figure 3.

(a) Original (b) Encrypted with ECB

Figure 3: ECB maintains data patterns.

Protocols which do not provide integrity protection are also more exposedto replay attacks when the ECB mode is used.

The ECB mode is ideal for a short amount of data, such as an encryptionkey. Thus, if we want to transmit a DES key securely, ECB is the appropriatemode to use.

4

Page 5: Block Cipher Modes of Operation and CMAC for Authentication

1.1.2 Cipher Block Chaining (CBC)

To overcome the security deficiencies of ECB, we would like a technique inwhich the same plaintext block, if repeated, produces different ciphertextblocks. The Cipher Block Chaining (CBC) mode of operation features thecombining (hence the word “chaining”) of each plaintext block with the pre-vious ciphertext block by means of XORing. This way our requirement issatisfied.

The CBC mode requires an initialization vector (IV), which is combinedwith the first plaintext block. The IV does not need to be secret, but itmust be unpredictable and its integrity must be preserved; the generation ofIVs will be discussed later on. Like the ECB mode, the CBC mode requirespadding when the plaintext size is not an integer multiple of the block sizein use.

The mode of operation is the following:

CBC encryption: C1 = CIPHk(P1 ⊕ IV )Cj = CIPHk(Pj ⊕ Cj−1) for j = 2...n

Figure 4: CBC encryption.

CBC decryption: P1 = CIPH−1k (C1)⊕ IV

Pj = CIPH−1k (Cj)⊕ Cj−1 for j = 2...n

In CBC encryption, the input block to each forward cipher operation (butthe first one) depends on the previous encrypted block; therefore, it is notpossible to perform such operations in parallel. Each CBC decryption opera-tion, however, only takes as inputs ciphertext blocks, thus allowing multipleoperations to occur in parallel. For the same reason, random access to theblocks is possible when decrypting.

5

Page 6: Block Cipher Modes of Operation and CMAC for Authentication

Figure 5: CBC decryption.

Due to block chaining, bit errors in a single ciphertext block cause cor-ruption of the corresponding decrypted block and of its successor. A one-bitchange may produce errors in any bit position of the current decrypted blockand inverts the corresponding bit in the following block.

A specific problem exists concerning the IV. An exposed IV might allow aman-in-the-middle (MITM) to change the IV value in-transit. Changing theIV changes only the deciphered plaintext for the first block, without garblingthe second block. Any or all bits of the first block plaintext can be changedsystematically with complete control. In marked contrast, when ciphertextis changed in CBC mode, it does change the next block plaintext bit-for-bit,but it also garbles the plaintext for the current block and so is easily detected.

An obvious solution to prevent deliberate MITM changes to the firstblock by altering the IV is to encipher the IV. Another possibility is touse a message number value known to both parties to produce the IV bymeans of ciphering. Techniques to reset the message number and maintainsynchronization would of course be required.

We must, however, bear in mind that CBC does not provide integrity, butonly confidentiality. If higher assurance of message integrity are required,authentication (which ensures integrity) might be necessary.

Propagating Cipher Block Chaining (PCBC) The Propagating Ci-pher Block Chaining (PCBC) mode is a variant of the CBC mode whichwas designed to propagate small errors (one-bit errors) in the ciphertext.Encryption and decryption routines are as follows:

PCBC encryption: Ci = CIPHk(Pi ⊕ Pi−1 ⊕ Ci−1), P0 ⊕ C0 = IV

PCBC decryption: Pi = CIPH−1k (Ci)⊕ Pi−1 ⊕ Ci−1, P0 ⊕ C0 = IV

6

Page 7: Block Cipher Modes of Operation and CMAC for Authentication

Since a single-bit error in a cipherblock thus affects all subsequent blocks,the entire message is very likely to be rejected. Whether this is a desirablefeature for a mode of operation largely depends on the application. In somecases, a one-bit change may indicate a possible attack; it is therefore mostpreferrable to discard the entire message. On the other hand, when bit errorsare more likely to be introduced by the transmission line, rather than by amalicious user, resilience of the data may be favourable.

The PCBC mode of encryption has not been formally published as a fed-eral or national standard, and it does not have widespread general support. Itwas used in Kerberos v4, but was abandoned starting from version 5 becausethe exchange of two adjacent blocks does not affect subsequent blocks.

As a matter of fact, when Ci and Ci+1 are received in order:

Pi = CIPH−1k (Ci)⊕ Pi−1 ⊕ Ci−1

Pi+1= CIPHk−1(Ci+1)⊕ Pi ⊕ Ci

= CIPH−1k (Ci+1)⊕ CIPH−1

k (Ci)⊕ Ci ⊕ Ci−1 ⊕ Pi−1

Pi+2= CIPH−1k (Ci+2)⊕ Pi+1 ⊕ Ci+1

= CIPH−1k (Ci+2)⊕ CIPH−1

k (Ci+1)⊕ CIPH−1k (Ci)⊕ Ci+1 ⊕ Ci⊕

⊕Ci−1 ⊕ Pi−1

When Ci and Ci+1 are exchanged:

Pi = CIPH−1k (Ci+1)⊕ Pi−1 ⊕ Ci−1

Pi+1= CIPH−1k (Ci)⊕ Pi ⊕ Ci+1

= CIPH−1k (Ci+1)⊕ CIPH−1

k (Ci)⊕ Ci+1 ⊕ Ci−1 ⊕ Pi−1

Pi+2= CIPH−1k (Ci+2)⊕ Pi+1 ⊕ Ci

= CIPH−1k (Ci+2)⊕ CIPH−1

k (Ci+1)⊕ CIPH−1k (Ci)⊕ Ci+1 ⊕ Ci⊕

⊕Ci−1 ⊕ Pi−1

The two expressions for Pi+2 are identical.

1.1.3 Cipher Feedback (CFB)

The Cipher Feedback (CFB) mode of operation turns the underlying blockcipher into a stream cipher. A stream cipher is a symmetric cipher whereplaintext bits are combined with a pseudorandom cipher bitstream, called

7

Page 8: Block Cipher Modes of Operation and CMAC for Authentication

a keystream. The CFB mode of operation is very close to the CBC mode.It entails the feedback of ciphertext segments which are ciphered to gener-ate output blocks; the latter are then XORed with the plaintext to produceciphertext (whereas in the CBC mode the XOR operation precedes the ci-phering). For this mode of operation the plaintext size need not be a multipleof the block size. As a matter of fact, a further parameter s, named the seg-ment size, is considered; it can assume any value between 1 and the blocksize b. The plaintext is thus decomposed into n segments P#

j , which are

encrypted into n ciphertext segments C#j .

The algorithm operates as follows:

CFB encryption: I1 = IV

Ij = LSBb−s(Ij−1)||C#j−1 for j = 2...n

Oj = CIPHk(Ij) for j = 1...n

C#j = P#

j ⊕MSBs(Oj) for j = 1...n

Figure 6: CFB encryption.

CFB decryption: I1 = IV

Ij = LSBb−s(Ij−1)||C#j−1 for j = 2...n

Oj = CIPHk(Ij) for j = 1...n

P#j = C#

j ⊕MSBs(Oj) for j = 1...n

In both CFB encryption and decryption, the IV is enciphered to producethe first output block. The s most significant bits of the first output block(of length b) are then XORed with the first plaintext segment, while theb− s least significant bits are discarded. Starting from the second iteration,

8

Page 9: Block Cipher Modes of Operation and CMAC for Authentication

Figure 7: CFB decryption.

the b − s least significant bits of the previous input block are concatenatedwith the previous ciphertext segment to form the current input block. Thisoperation is equivalent to shifting the previous input block to the left by spositions and replacing the s least significant bits of the result with the lastciphertext segment.

In CFB encryption, just like CBC encryption, the input block to each ci-pher operation depends on the result of the previous one. Although encryp-tion cannot be executed in parallel on multiple blocks, a form of pipeliningis possible, since the only encryption step that requires the actual plaintextis the last. This is useful when low latency between the arrival of plaintextand the output of the corresponding ciphertext is required (e.g., in someapplications of streaming media).

Decryption can be performed in parallel.A further advantage of the CFB mode is that the cipher function is only

ever used in the forward direction.

The CFB mode of operation relates to bit errors in the opposite way withrespect to the CFB mode. A single-bit error in a ciphertext block results inan error in the same bit position of the corresponding decrypted block andmay affect the following db/se segments in an unpredictable way. Bit errorsin the IV affect, at a minimum, the decryption of the first ciphertext segmentand possibly following segments, depending on the position of the rightmostbit error in the IV; in general, a bit error in the ith position (counting fromthe left) affects the decryption of the first di/se segments.

The CFB mode is exposed to the risk of intentional introduction of biterrors in specific bit positions when it is used with an underlying block cipherwhich does not provide data integrity. Unlike other modes of operation,however, the existence of such errors may be inferred by their randomizing

9

Page 10: Block Cipher Modes of Operation and CMAC for Authentication

effects on the following ciphertext segments.The insertion or deletion of bits into a ciphertext segment spoils the

synchronization of the segment boundaries. The decryption of the subsequentsegments will almost certainly be incorrect until synchronization is restored.When the 1-bit CFB mode (i.e., the CFB mode with a segment size of 1 bit)is used, the synchronization is automatically restored after b + 1 segments.For other values of s the synchronization must be restored manually.

Attacking the OpenPGP CFB mode The OpenPGP Message Formatis a very popular and commonly used format for signing and encrypting datafiles, particularly for signing and encrypting email. The formats describedin the OpenPGP RFC have been implemented in a wide variety of popu-lar freeware and commercial encryption products. Symmetric encryption inOpenPGP is performed using a variant of the standard CFB mode. Themain difference with the OpenPGP variant is that a plaintext initializationvector, as described above, is not used, but instead a random block R is en-crypted as the first block of ciphertext. Two bytes of R are repeated in thesecond block in order to quickly check whether the session key K is incorrectupon decryption. This “quick check” is really an integrity check on the keyand it is this ad-hoc integrity mechanism, used in a mode of operation thatwasn’t designed to accommodate it, that allows the attack.

The successful outcome of the attack relies on two assumptions: 1) thefirst 2 bytes of the first plaintext block can be easily guessed, and 2) an oracleO that, when given a purported ciphertext encrypted using the OpenPGPCFB mode of operation with a given key, will correctly determine whether ornot the integrity check was successful is available. Both these assumptionsare reasonable. As a matter of fact, compression algorithms are very oftenused along with the OpenPGP CFB mode; the first 2 bytes of the message aretherefore likely to be a known packet tag and a known compression algorithmidentifier. This justifies the first assumption. As to the second assumption,mechanisms to inform the end user that the integrity check failed on theencrypted message are very likely to be available on a system implementingthe OpenPGP CFB mode. If, however, this should not be the case, timingattacks would always be possible, since the decryption of the message doesnot start if the integrity check fails.

The knowledge of the first 2 bytes of the message enable a malicious user,after an initial setup of about 215 oracle queries, to find out 16 bits of anyblock with 215 queries for each block. Further details, mathematical proofs,as well as extensive discussion of possible solutions, is given in [4].

10

Page 11: Block Cipher Modes of Operation and CMAC for Authentication

1.1.4 Output Feedback (OFB)

The Output Feedback (OFB) mode of operation, just like CFB, converts theunderlying block cipher into a stream cipher. It features the iteration ofthe forward cipher function on an IV to generate keystream blocks, whichare combined with the plaintext blocks by means of XORing. The plaintextsize is not requested to be an integer multiple of the block size. The lastblock may be a partial block of size u; in that case, it is XORed with the umost significant bits of the last keystream block to produce the last (partial)ciphertext block.

It is defined as follows:

OFB encryption: I1 = IVIj = Oj−1 for j = 2...nOj = CIPHk(Ij) for j = 1...nCj = Pj ⊕Oj for j = 1...n− 1C∗n = P ∗n ⊕MSBu(On)

Figure 8: OFB encryption.

OFB decryption: I1 = IVIj = Oj−1 for j = 2...nOj = CIPHk(Ij) for j = 1...nPj = Cj ⊕Oj for j = 1...n− 1P ∗n = C∗n ⊕MSBu(On)

Both encryption and decryption make use of recurrent ciphering of an IV;this prevents from performing multiple cipher operations at the same time.Nonetheless, if the IV is known, then the keystream blocks can be pre-computed, prior to the availability of the plaintext or ciphertext data.

11

Page 12: Block Cipher Modes of Operation and CMAC for Authentication

Figure 9: OFB decryption.

The OFB requires the IV to be a nonce, i.e. that the IV be unique for everymessage that is encrypted with a given key. When this requirement is notmet, the confidentiality of the encrypted message may be compromised. If aplaintext block is known to a malicious user, the latter can easily reconstructthe corresponding keystream block from the ciphertext block. Reusage ofthe same IV therefore enables the malicious user to gain knowledge of thecorresponding block of information by simply XORing the ciphertext blockwith the keystream block. The same holds when any of the input blocksto the forward cipher is designated as the IV for the encryption of anothermessage under the same key.

Bit errors within a ciphertext block only affect the decryption of that block;flipping a bit in the ciphertext produces a flipped bit in the plaintext at thesame location. This property is useful, in that it allows many error correctingcodes to function normally even when applied before encryption. However,OFB is less resistant to message stream modification attacks. An attackermay in fact systematically change bits of his choosing in every block andcorrespondingly alter the checksum part of the message in such a way thatthe modifications will not be detected by an error-correcting code.

Conversely, bit errors in the IV affect the decryption of all ciphertextblocks.

1.1.5 Counter (CTR)

As with the OFB mode of operation, the Counter (CTR) mode of operation,also known as Segmented Integer Count (SIC), makes a block into a streamcipher. Keystream blocks are generated by encrypting a sequence of inputblocks, named counters. The word “counter” assumes here a broader mean-ing; it can be any function which is known to produce a sequence of blocks

12

Page 13: Block Cipher Modes of Operation and CMAC for Authentication

that do not repeat for a long time. An actual counter is the simplest andmost popular of such functions. The property that all counter blocks mustbe different does not apply to a single message: across all of the messagesthat are encrypted under a given key, counters must be distinct.

Given a sequence of counters T1, T2, ..., Tn, the CTR mode is defined asfollows:

CTR encryption: Oj= CIPHk(Tj) for j = 1...nCj = Pj ⊕Oj for j = 1...n− 1C∗n= P ∗n ⊕MSBu(On)

Figure 10: CTR encryption.

CTR decryption: Oj= CIPHk(Tj) for j = 1...nPj = Cj ⊕Oj for j = 1...n− 1P ∗n= C∗n ⊕MSBu(On)

Figure 11: CTR decryption.

13

Page 14: Block Cipher Modes of Operation and CMAC for Authentication

The CTR mode can operate with input plaintexts whose size is not aninteger multiple of the block size b. In that case, the last block C∗n will be apartial block.

Both CTR encryption and decryption work on counter blocks and plain-text/ciphertext blocks independent from one another; multiple forward ci-pher functions can thus be performed in parallel, providing greater hard-ware efficiency than all other modes of operation. The only limitation is theamount of parallelism that can be achieved on a given machine.

In addition, the CTR mode provides true random access to any particularciphertext block. The forward cipher function can also be applied to each ofthe counters in advance, so that decryption can start as soon as ciphertextblocks are available.

A further advantage of the CTR mode is its simpicity, since the cipheralgorithm is only needed for encryption, while simple XOR operations areused for decryption. This matters most when the decryption algorithm differssubstantially from the encryption algorithm, as it does for AES.

In order to ensure the uniqueness of each counter block, two aspects mustbe taken into account. First, an appropriate incrementing function thatgenerates the counter blocks from any initial counter block must guaranteethat counters do not repeat within a given message. Second, the initialcounter blocks for every message must be chosen in such a way that counterblocks do not repeat across all messages that are encrypted under a givenkey.

The Standard Incrementing Function The standard incrementing func-tion can apply either to an entire block or to a part of a block. Let m bethe number of bits involved in the incrementation. This m-bit string can beregarded as a binary non-negative number x; the incrementing function takesthe binary number x and returns x + 1 mod 2m. This way, the uniquenessrequirement for the counter blocks is satisfied within a given message of nblocks, provided that n ≤ 2m.

Choice of the Initial Counter Blocks Two possible approaches arediscussed here.

The first approach entails the sequential encryption of all the messagesthat are ever encrypted under a given key. Any initial block of b bits maybe chosen as the initial counter block for the first message. For all successivemessages, the initial counter block is obtained by applying the standardincrementing function to the last counter block of the previous message.

14

Page 15: Block Cipher Modes of Operation and CMAC for Authentication

This approach requires that the total number of blocks, across all messages,be at most 2m; care should also be taken to ensure the proper sequencing ofthe messages.

A second approach lies in the assignment of a unique identifier (i.e., anonce) to every message. The nonce is a (b−m)-bit string that is incorporatedin every counter block of a given message. To ensure that it is used only once,it should be time-variant or generated with enough random bits to guaranteea probabilistically insignificant chance of collision. The incrementing functionis applied to the remaining m bits. The nonce and the actual counter can besubsequently concatenated, added or XORed to produce the unique counterblock.

1.2 Generation of Initialization Vectors

Four of the modes of operation hereby described (i.e., all but the ECB mode)require an initialization vector. For the CBC and CFB modes, the IV mustbe unpredictable. This means that, given a plaintext, it must not be possibleto predict the IV that will be associated to it in advance of its generation. Amethod to produce unpredictable IVs is to apply the forward cipher functionto a nonce. As an alternative, an unpredictable IV may be obtained byresorting to a FIPS-approved random number generator.

The OFB mode does not require the IV to be unpredictable, but it mustbe unique to the execution of the encryption operation. It can be a nonce ora message number. The same observation applies to the CTR mode, whereeach of the counter blocks may be regarded as an IV.

1.3 Padding-related issues

1.3.1 Padding techniques

For three of the modes of operation formerly described, the input plaintextmust be a sequence of complete blocks (for the ECB and CBC modes) orsegments (for the CFB mode). If the initial plaintext does not satisfy thisproperty, extra bits must be appended at the end of the last (partial) blockor segment to complete it. Two simple ways of padding a message are bitpadding and byte padding.

A bit padding scheme is described in RFC1321 and was originally usedwith the DES algorithm. A single set (‘1’) bit is added at the trailing endof the message and then as many reset (‘0’) bits as required are appended.This method can be used to pad blocks of any size, not necessarily an integer

15

Page 16: Block Cipher Modes of Operation and CMAC for Authentication

number of bytes. For the above padding method, the padding bits can beremoved unambiguously, provided that the receiver can determine that themessage is indeed padded. In order to ensure that the receiver does not mis-takenly remove bits from an unpadded message, the sender may be requiredto pad every message, even though the last block is already complete. Inthat case, an entire block of padding is added.

Byte padding schemes are defined in a number of official papers. In ANSIX.923 a byte padding scheme is specified for use with blocks whose size is aninteger number of bytes. Null bytes are padded and the last byte defines thepadding boundaries or the number of padded bytes. ISO 10126 describes avery similar padding scheme which uses random bytes instead of null bytes.In the PKCS7 scheme, defined in RFC3852, the value of each padding byteis the total number of padded bytes (e.g. N bytes are added, each of valueN). Finally, the zero padding scheme pads all bytes with null bytes.

Besides incrementing the amount of data to be transmitted, padding mayhave other outcomes. Padding with random values may be necessary whena regular, known data pattern needs to be sent; this has the side benefitof making some kinds of cryptanalysis more difficult. However, in somecircumstances the use of padding may expose the exchange of a message totiming attacks.

1.3.2 Ciphertext stealing (CTS)

In some applications, such as data streaming, or when a number of messageswhose sizes do not align to block boundaries need to be transmitted, the use ofpadding may be inconvenient. Some nifty techniques have been developed toavoid the transmission of extra ciphertext; one of them is ciphertext stealing(CTS).

In order to produce ciphertext of the same length as the correspond-ing plaintext, we must avoid adding extra, unneeded information, such aspadding. Block ciphers, however, need entire plaintext blocks to performencryption. One may at this point decide to pad the incomplete block, en-crypt it and discard as many bits of the corresponding ciphertext block asthe padding bits, mistakenly judging them unnecessary. This is not so. Sincea block cipher is being used, no direct kinship between a bit in the plaintextand the corresponding bit in the ciphertext can be assumed (or else the blockcipher would be a stream cipher!) and all bits in the ciphertext are poten-tially necessary to reconstruct a single bit of plaintext. The CTS techniquecan be applied to the ECB and CBC modes of operation and provides a

16

Page 17: Block Cipher Modes of Operation and CMAC for Authentication

workaround to this problem. The goal is achieved at the cost of an increasedcomplexity of the encryption and decryption process. The encryption anddecryption algorithms for the ECB mode only are described below.

Encryption:

1. En−1 = CIPHk(Pn−1)

2. C∗n = MSBm(En−1)

3. Dn = Pn||LSBb−m(En−1)

4. Cn−1 = CIPHk(Dn)

Decryption:

1. Dn = CIPH−1k (Cn−1)

2. En−1 = C∗n||LSBb−m(Dn)

3. Pn = MSBm(Dn)

4. Pn−1 = CIPH−1k (En−1)

During encryption, all plaintext blocks except the last one are encryptednormally. After the second-to-last block has been encrypted, the m mostsignificant bits are taken to create the last partial ciphertext block. Theremaining bits are then appended to the last incomplete plaintext block andthe block thus obtained is enciphered to create the second-to-last ciphertextblock. This way we transmit as many bits as were in the original message.

The receiver normally decrypts all blocks except the last one. The mmost significant bits of the plaintext block obtained from the decryptionof the second-to-last ciphertext block give the last plaintext block, whereasthe remaining b −m bits are concatenated to the last ciphertext block anddecrypted, yielding the second-to-last plaintext block.

As we can notice, a portion of the second-to-last plaintext block is en-crypted twice and some additional bit-wise operations are required. Allow-ing for even higher complexity when the CBC mode is used, and bearingin mind that really short messages (i.e. messages that fit in less than onefull block) can still not be encrypted without padding, the CTS techniqueis nowadays hardly ever worthwhile. The CBC mode of operation is beinglargely replaced by the CTR mode, which does not need padding.

17

Page 18: Block Cipher Modes of Operation and CMAC for Authentication

1.4 Related-mode attacks

Block ciphers are often proposed with several variants, in terms of a differentsecret key size and corresponding number of rounds. The so called “related-cipher attack” model refers to a situation in which some ciphers are related,in the sense that they are exactly identical to each other, differing only in thekey size and most often also in the total number of rounds. The knowledgethat one cipher is being used and the availability of an oracle which providesthe forward and inverse cipher functions of a related cipher can be exploitedin order to attack the exchange of information enciphered using the firstcipher.

The concept has then been extended to a larger class of related models,in particular to cipher encryptions with different block cipher modes of oper-ation, but with the underlying block cipher being identical. This new modelhas been named a “related-mode attack” model. It has been shown thatwhen an adversary has access to an oracle for any one mode of operation(ECB, CBC, CFB, OFB, CTR), then almost all other related cipher modescan be easily attacked. Examples of such attacks are briefly outlined in thefollowing paragraphs. Further examples may be found in [6].

1.4.1 Exploiting an ECB Oracle to attack the CTR mode

We suppose the attacker has access to an ecnryption-only oracle O underECB mode and strives to attack another related cipher in the CTR mode.Let Pi and Ci denote, respectively, the current plaintext and ciphertext blocksof the related-cipher mode being attacked, while P ′i and C ′i denote, respec-tively, the current plaintext and ciphertext blocks used in the interactionwith the oracle O. Having intercepted Ci, the attacker chooses P ′i = C0 + ito feed the ECB encryption and hence obtains C ′i = CIPHk(C0 + i). SinceCi = CIPHk(C0 + i)⊕Pi, he can easily compute Pi = Ci⊕C ′i. In summary,he only needs one chosen plaintext (CP) query encrypted under ECB toobtain the plaintext block corresponding to any ciphertext block encryptedunder CTR.

1.4.2 Exploiting a CBC Oracle to attack the CTR mode

The adversary can in a similar way attack the CTR mode having access toa CBC encryption-only oracle. First the adversary queries the encryptionoracle with the the plaintext block P ′i−1 and gets the ciphertext block C ′i−1.He then chooses P ′i = C ′i−1⊕ (C0 + 1) and queries again the oracle, obtainingC ′i = CIPHk(C ′i−1⊕P ′i ) = CIPHk(C0 + 1). This value is directly related toan intermediate value in CTR, since Ci = Pi ⊕ C ′i, and enables the attacker

18

Page 19: Block Cipher Modes of Operation and CMAC for Authentication

to find Pi. On the whole, two CP queries under CBC are required to obtaina block enciphered under CTR.

2 The CMAC Mode for Authentication

2.1 Introduction

The CMAC is a block cipher-based message authentication code algorithmwhich may be used to provide assurance of the authenticity and, hence, theintegrity of binary data. Its role is analogous to the standard hash function-based MAC (HMAC) and it may be appropriate for information systemswhere an approved block cipher is more readily available than an approvedhash function.

The ancestor of the CMAC mode for authentication is the Cipher BlockChaining MAC (CBC-MAC) algorithm, a block cipher-based algorithm tocreate MACs that has serious security deficiencies. A first improvementof the CBC-MAC was proposed by Black and Rogaway and submitted toNIST under the name XCBC. Iwata and Kurosawa provided a further refine-ment, which was initially submitted as the One-Key CBC-MAC (OMAC)and, later, as OMAC1, which included additional security analysis and effi-ciently reduced the key size of XCBC. CMAC is equivalent to OMAC1.

CMAC, like any well-designed MAC algorithm, provides stronger assuranceof data integrity than a checksum or an error detecting code. The verificationof a checksum or an error detecting code is designed to detect only accidentalmodifications of the data, while CMAC is designed to detect intentional,unauthorized modifications of the data, as well as accidental modifications.

2.2 Cipher Block Chaining MAC (CBC-MAC)

The CMAC mode addresses many of the weaknesses of the original CipherBlock Chaining MAC (CBC-MAC). In order to better understand its mech-anism, as well as the attacks to which a message authentication code (MAC)may be exposed, a brief overview of the CBC-MAC, along with its drawbacks,is provided in the following paragraphs.

19

Page 20: Block Cipher Modes of Operation and CMAC for Authentication

2.2.1 Description

In the Cipher Block Chaining MAC, the message is encrypted with someunderlying block cipher algorithm using the CBC mode of operation and zeroIV, so as to create an interdependence between each block and its predecessor.As a consequence, a change to any of the plaintext bits will cause the finalencrypted block to change in a way that cannot be predicted or counteractedwithout knowing the key to the block cipher. The final ciphertext block istaken as the message authentication code (MAC) for the current message.

2.2.2 Weaknesses

Given a secure underlying block cipher, the CBC-MAC mode for authenti-cation is secure for fixed-length messages (i.e., when the two parties agreedon a message length and any message of a different length will be discarded,as considered inauthentic). However, it is not secure for variable-length mes-sages. An attacker who knows two distinct messages, m′ and m′′, with theirassociated CBC-MACs, t′ and t′′, can produce a third message m∗, whoseCBC-MAC will also be t′′. This is done by simply XORing the first plaintextblock of m′′ with t′ and then chaining m′ with the thus modified m′′:

m∗ = m′‖[(m′′1 ⊕ t)‖m′′2‖...‖m′′q ]

As a matter of fact, when the receiver computes the CBC-MAC over thereceived message m∗, the first block of m′′ will be XORed with the last ci-phertext block of m′, which is in fact t′. XORing of two identical bit-vectorsyields the zero vector, which results, in practice, in computing the CBC-MACover m′′ only, “undoing” all past history (represented by m′):

MACIV =0(m∗)= MACIV =0(m

′‖[(m′′1 ⊕ t)‖m′′2‖...‖m′′q ])= MACIV =t((m

′′1 ⊕ t)‖m′′2‖...‖m′′q)

= MACIV =0(m′′)

= t′′

The MAC verification will therefore succeed and the message will be mistak-enly accepted as authentic.

Another security problem of the CBC-MAC arises when the same key isused for CBC encryption and CBC-MAC. Although reuse of a key for dif-ferent purposes is bad practice in general, in this particular case the mistakemay lead to an unparallaled attack.

20

Page 21: Block Cipher Modes of Operation and CMAC for Authentication

Suppose a message m = m1‖m2‖...‖mq is encrypted using the CBC modeunder the key k, yielding the ciphertext c1‖c2‖...‖cq. We here assume thatthe IV for the encryption is obtained by forward-ciphering a bit-vector (e.g.,a nonce), which we will call m0. The same key is then used to produce aCBC-MAC t for the IV and the message. An attacker may now change everybit before the last ciphertext block cq, and the MAC will still be valid. Thisis because t = CIPHk(mq⊕cq−1) = cq, so as long as the last ciphertext blockremains unaltered, the CBC-MAC verification will succeed. This is also thereason why inexperienced users often make such a gross mistake: it allowsto encrypt the message and compute its MAC in a single pass, increasingperformance by a factor of two. This also shows that the CBC-MAC cannotbe used as a collision resistant one-way function: given a key, it is trivial tofind a different message which maps to the same MAC.

2.3 CMAC Specification

2.3.1 Subkeys generation

The CMAC mode for authentication requires two additional parameters, be-sides the block cipher key. These parameters, named the subkeys, K1 andK2, are derived from the block cipher key; they must be kept secret. Thesubkeys are fixed for any invocation of CMAC under a given key. As a con-sequence, they do not need to be recomputed anew every time; they may,instead, be calculated once and stored along with the block cipher key. Thesubkeys are generated as follows:

1. L← CIPHk(0b)

2. if MSB1(L) = 0 then K1 ← L << 1else K1 ← (L << 1)⊕Rb

3. if MSB1(K1) = 0 then K2 ← K1 << 1else K2 ← (K1 << 1)⊕Rb

In step 1, 0b indicates the bit string that consists of b 0s. The value that isobtained from applying the forward cipher function to the zero string mustalso be kept secret.In step 2 and 3 the parameter Rb appears; this value is a bit string thatis completely determined by the block size b. For example, for the AESunderlying block cipher the block size is 128 bits and Rb = 012010000111;for the other currently approved block cipher, TDEA, the block size is 64bits and the corresponding value of Rb is 05911011. Given a block size b, inorder to find Rb we must find the lexicographically first among all irreducible

21

Page 22: Block Cipher Modes of Operation and CMAC for Authentication

polynomials of degree b having the minimum possible number of nonzeroterms. If we let that polynomial be ub + cb−1u

b−1 + ... + c2u2 + c1u + c0,

then Rb is the bit string cb−1cb−2...c2c1c0. The generation of K1 and K2 isessentially equivalent to multiplication by u and u2, respectively, within theGalois field that is determined by this polynomial.

2.3.2 CMAC generation

Once the subkeys K1 and K2 have been computed (or retrieved, togetherwith the shared secret K), the CMAC can be generated from the plaintextmessage. Unlike CBC-MAC, CMAC is secure for variable-length messages.Mathematical proof is provided in [7]. The CMAC is generated as follows:

1. if Mlen = 0 then n← 1else n← dMlen/be

2. if M∗n is a complete block then Mn ← K1 ⊕M∗

n

else Mn ← K2 ⊕ (M∗n‖10j), where j = nb−Mlen − 1

3. C0 ← 0b

4. for i← 1 to n doCi ← CIPHk(Ci−1 ⊕Mi)

5. T ←MSBTlen(Cn)

The two subkeys K1 and K2 are used to mask the last block M∗n. When

the latter is a complete block, then it is simply masked with K1 and thesequence of blocks M1M2...Mn is the formatted message. When the lastblock is incomplete, a padding string is appended to it, composed by a single‘1’ followed by as many ‘0’s (possibly none) as are necessary to complete theblock. The padded block is subsequently masked with K2, yielding Mn.

After the initial formatting, the following step is identical to the CBC-MAC algorithm. The final step truncates the last CBC output block accord-ing to the MAC length parameter.

The formatting of the message does not need to complete for the CBCoperations to start. These two processes may occur in parallel.

2.3.3 CMAC verification

After an authorized party has applied the CMAC generation process to thedata to be authenticated to produce a MAC, any authorized party can applythe verification process to the received data and the received MAC. Successfulverification provides assurance of data authenticity and, hence, of integrity.

22

Page 23: Block Cipher Modes of Operation and CMAC for Authentication

Figure 12: Two cases of CMAC generation.

The verification of the MAC involves two steps. Prior to verification, thereceived data must be decrypted using the appropriate mode of operationand underlying algorithm. The CMAC algorithm is applied to the decrypteddata and a MAC is generated. The result is then compared with the receivedMAC. Upon successful comparison, the verification process terminates suc-cesfully.

2.4 Security issues

2.4.1 Length of the MAC

A parameter that has great incidence on security-related issues is the lengthof the MAC. Choosing an appropriate length for the MAC may prove fun-damental in resisting to guessing attacks.

The verification process determines whether an alleged MAC is a validoutput of the CMAC generation process applied to the message the MACcame with. If the verification process fails, then the message is undoubtedlyinauthentic i.e., it was not produced by an authorized party, and is thereforediscarded. Upon successful verification, CMAC provides sufficient assurancethat the message is authentic and, hence, was not corrupted in transit. Thisassurance, however, is not absolute. An attacker might have, for instance,simply guessed the correct MAC for the message. By selecting a MAC atrandom from the set of all possible bit strings of length Tlen, the attackerhas a probability of 1/2Tlen that his or her guess will be correct. As a con-sequence, using a longer MAC provides better protection against guessingattacks. On the other hand, larger values of Tlen require more storage spaceand bandwidth, which may not be acceptable for some applications.

The attacker might also repeatedly attempt to guess the right MAC,thereby increasing his chances of succeeding in the attack. For that reason,

23

Page 24: Block Cipher Modes of Operation and CMAC for Authentication

care should be taken to ensure that the maximum number of unsuccessfulCMAC verifications on a given system be limited.

For most applications, a value of at least 64 bits should provide sufficientprotection. Choosing a length that is less than 64 bits should be accompa-nied by careful pondering of the risks of accepting an inauthentic messageas authentic and by restricing the number of unsuccessful attempts. Morespecific guidance in the choice may be quantified in terms of two parameters:MaxInvalids, a limit on the number of times that the verification processmay fail before the key is retired, and Risk, the highest acceptable probabil-ity for an inauthentic message to pass the verification process. Tlen shouldthen satisfy the following inequality:

Tlen ≥ log2(MaxInvalids/Risk)

A simple example may be useful to understand the above formula. Supposewe want at most 25% of the messages we receive to be mistakenly acceptedas authentic; we also allow only one attempt. The resulting value for Tlen isthus 2 bits. This is correct, since there is a probability of 1/4 that a malicioususer can guess the correct MAC out of the 4 possible 2-bit patterns.

We now increase the number of attempts to two, always with a risk of25%. The above equation yields Tlen = 3. As a matter of fact:

P [ correct guess ]=P [1st guess correct]++P [2nd guess correct |1st guess incorrect]

= 18

+ 17

78

= 14

2.4.2 Message span of the key

The message span of a given key is the total number of messages to whichthe CMAC algorithm is applied under the same key. The message span of akey affects the security of the system against attacks that are based on thedetection of a pair of distinct messages which lead to the same MAC beforeits truncation. Such an event is called a collision. An attacker might exploita collision to append the MAC of a message to a new message whose contentmay largely differ from the original one.Collisions cannot be utterly avoided, because the number of all possible mes-sages is much higher than the number of all possible MACs. However, col-lisions should not occur among the messages for which MACs are actuallygenerated with a given key. The probability that at least one collision ac-tually occurs during the lifetime of the key depends on the message span of

24

Page 25: Block Cipher Modes of Operation and CMAC for Authentication

the key, relative to the block size of the underlying block cipher. For a givenblock size b, a collision is expected to exist among a set of 2b/2 messages. Themessage span of a key should therefore be reasonably limited, with respectto the value of the data involved in the exchange.

For general-purpose applications, the message span is measured in termsof the total number of messages the same key is used with. When the blocksize of the underlying block cipher is 128 bits, such as with AES, the messagespan should be limited to no more than 248 messages; when the block size is64 bits, as it is the case with TDEA, the limit is 221 messages.For applications which require a higher level of security, the message span isexpressed in terms of message blocks. In this case, when the block size ofthe underlying algorithm is 128 bits, a message span of at most 248 messageblocks (222 GB) is recommended; for a block size of 64 bits, the recommendedlimit is 221 blocks (16 MB).Within these limits, the probability that a collision will occur is proved tobe less than 10−9 for a block size of 128 bits and less than 10−6 for a blocksize of 64 bits.

Sometimes the limit for the message span of a given key may be establishedby restraining the time span during which the key remains in use (i.e., itscryptoperiod).

2.4.3 Protection against replay attacks

The successful verification of the MAC gives assurance that the source of themessage executed the MAC generation algorithm. However, this does notensure that the sender of the message is the actual source that produced it.An attacker may in fact intercept a legitimate message with its MAC, store itand send it at a later time, claiming to be an authorized party. Therefore, theCMAC algorithm does not inherently provide any protection against replayattacks.Such protection must be provided, instead, by the protocol or applicationthat is using the CMAC mode to authenticate its messages by insertingsome identifying information at the beginning of the message. For instance,a sequential number, a timestamp, a nonce etc. may be incorporated in eachmessage, in order to make it possible to detect replayed messages, out-of-sequence messages or missing messages.

25

Page 26: Block Cipher Modes of Operation and CMAC for Authentication

References

[1] Morris Dworkin. Recommendation for Block Cipher Modes of Operation.Methods and techniques. NIST Special Publication 800-38A, 2001.http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf

[2] Morris Dworkin. Recommendation for Block Cipher Modes of Operation:The CMAC Mode for Authentication. NIST Special Publication 800-38B,2001.http://csrc.nist.gov/publications/nistpubs/800-38B/SP 800-38B.pdf

[3] Wikipedia. The free encyclopedia.http://www.wikipedia.org/

[4] S. Mister, R. Zuccherato. An Attack on CFB Mode Encryption As UsedBy OpenPGPhttp://eprint.iacr.org/2005/033.pdf

[5] W. Stallings. Cryptography and Network Security. Principles and Prac-tices. IV edition, Prentice-Hall, 2005.

[6] D. Wang, D. Lin, W. Wu. Related-Mode Attacks on CTR EncryptionModehttp://ijns.nchu.edu.tw/contents/ijns-v4-n3/ijns-2007-v4-n3-p282-287.pdf

[7] T. Iwata, K. Kurosawa. OMAC: One-Key CBC MAChttp://crypt.cis.ibaraki.ac.jp/omac/docs/omac.pdf

26