esp_packet_decrypt.c
Go to the documentation of this file.
1 /**
2  * @file esp_packet_decrypt.c
3  * @brief ESP packet decryption
4  *
5  * @section License
6  *
7  * SPDX-License-Identifier: GPL-2.0-or-later
8  *
9  * Copyright (C) 2022-2024 Oryx Embedded SARL. All rights reserved.
10  *
11  * This file is part of CycloneIPSEC Open.
12  *
13  * This program is free software; you can redistribute it and/or
14  * modify it under the terms of the GNU General Public License
15  * as published by the Free Software Foundation; either version 2
16  * of the License, or (at your option) any later version.
17  *
18  * This program is distributed in the hope that it will be useful,
19  * but WITHOUT ANY WARRANTY; without even the implied warranty of
20  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21  * GNU General Public License for more details.
22  *
23  * You should have received a copy of the GNU General Public License
24  * along with this program; if not, write to the Free Software Foundation,
25  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
26  *
27  * @author Oryx Embedded SARL (www.oryx-embedded.com)
28  * @version 2.4.0
29  **/
30 
31 //Switch to the appropriate trace level
32 #define TRACE_LEVEL ESP_TRACE_LEVEL
33 
34 //Dependencies
35 #include "ipsec/ipsec.h"
36 #include "ipsec/ipsec_inbound.h"
37 #include "esp/esp.h"
38 #include "esp/esp_packet_decrypt.h"
41 #include "aead/aead_algorithms.h"
42 #include "debug.h"
43 
44 //Check IPsec library configuration
45 #if (ESP_SUPPORT == ENABLED)
46 
47 
48 /**
49  * @brief Decrypt an incoming ESP packet
50  * @param[in] context Pointer to the IPsec context
51  * @param[in] sa Pointer to the SAD entry
52  * @param[in] espHeader Pointer to the ESP header
53  * @param[in,out] payload Payload data to be decrypted
54  * @param[in,out] payloadLen Actual length of the payload data
55  * @param[out] nextHeader Value of the next header field
56  * @return Error code
57  **/
58 
60  const EspHeader *espHeader, uint8_t *payload, size_t *payloadLen,
61  uint8_t *nextHeader)
62 {
63  error_t error;
64  size_t i;
65  uint8_t *data;
66  uint8_t *icv;
67  size_t length;
68  const CipherAlgo *cipherAlgo;
69  EspTrailer *espTrailer;
70  uint8_t iv[MAX_CIPHER_BLOCK_SIZE];
71 
72  //Check the length of the payload data
73  if(*payloadLen < (sa->ivLen + sizeof(EspTrailer) + sa->icvLen))
74  return ERROR_INVALID_PACKET;
75 
76  //Determine the length of the ciphertext
77  length = *payloadLen - sa->ivLen - sa->icvLen;
78 
79  //If the algorithm used to encrypt the payload requires an Initialization
80  //Vector (IV), then this data is carried explicitly in the payload field
81  osMemcpy(iv, payload, sa->ivLen);
82 
83  //Point to the ciphertext
84  data = payload + sa->ivLen;
85  //Point to the Integrity Checksum Value (ICV)
86  icv = data + length;
87 
88  //The SAD entry specifies the algorithms and keys to be employed for
89  //decryption (refer to RFC 4303, section 3.4.2)
90  cipherAlgo = sa->cipherAlgo;
91 
92 #if (ESP_CBC_SUPPORT == ENABLED)
93  //CBC cipher mode?
94  if(sa->cipherMode == CIPHER_MODE_CBC)
95  {
96  //The length of the ciphertext must be a multiple of the block size
97  if((length % cipherAlgo->blockSize) != 0)
98  return ERROR_INVALID_PACKET;
99 
100  //If a separate integrity algorithm is employed, then the receiver
101  //proceeds to integrity verification (refer to RFC 4303, section 3.4.3)
102  error = espVerifyChecksum(context, sa, espHeader, context->buffer,
103  sa->ivLen + length, icv);
104  //Any error to report?
105  if(error)
106  return error;
107 
108  //Initialize cipher context
109  error = cipherAlgo->init(&sa->cipherContext, sa->encKey, sa->encKeyLen);
110  //Any error to report?
111  if(error)
112  return error;
113 
114  //Perform CBC decryption
115  error = cbcDecrypt(cipherAlgo, &sa->cipherContext, iv, data, payload,
116  length);
117  //Any error to report?
118  if(error)
119  return error;
120  }
121  else
122 #endif
123 #if (ESP_CTR_SUPPORT == ENABLED)
124  //CTR cipher mode?
125  if(sa->cipherMode == CIPHER_MODE_CTR)
126  {
127  uint8_t counter[16];
128 
129  //The counter block is 128 bits, including a 4-octet nonce, 8-octet IV,
130  //and 4-octet block counter, in that order (refer to RFC 3686, section 4)
131  osMemcpy(counter, sa->encKey + sa->encKeyLen, 4);
132  osMemcpy(counter + 4, iv, 8);
133 
134  //The block counter begins with the value of one and increments by one
135  //to generate the next portion of the key stream
136  STORE32BE(1, counter + 12);
137 
138  //If a separate integrity algorithm is employed, then the receiver
139  //proceeds to integrity verification (refer to RFC 4303, section 3.4.3)
140  error = espVerifyChecksum(context, sa, espHeader, context->buffer,
141  sa->ivLen + length, icv);
142  //Any error to report?
143  if(error)
144  return error;
145 
146  //Initialize cipher context
147  error = cipherAlgo->init(&sa->cipherContext, sa->encKey, sa->encKeyLen);
148  //Any error to report?
149  if(error)
150  return error;
151 
152  //Perform CTR decryption
153  error = ctrDecrypt(cipherAlgo, &sa->cipherContext,
154  cipherAlgo->blockSize * 8, counter, data, payload, length);
155  //Any error to report?
156  if(error)
157  return error;
158  }
159  else
160 #endif
161 #if (ESP_CCM_8_SUPPORT == ENABLED || ESP_CCM_12_SUPPORT == ENABLED || \
162  ESP_CCM_16_SUPPORT == ENABLED)
163  //CCM AEAD cipher?
164  if(sa->cipherMode == CIPHER_MODE_CCM)
165  {
166  size_t aadLen;
167  uint8_t aad[12];
168  uint8_t nonce[11];
169 
170  //The components of the nonce are the salt with the IV (refer to RFC 4309,
171  //section 4)
172  osMemcpy(nonce, sa->encKey + sa->encKeyLen, 3);
173  osMemcpy(nonce + 3, iv, 8);
174 
175  //Two formats of the AAD are defined (refer to RFC 4309, section 5)
176  if(sa->esn)
177  {
178  //Reconstruct the 64-bit sequence number
179  uint64_t seq = ipsecGetSeqNum(sa, ntohl(espHeader->seqNum));
180 
181  //AAD Format with 64-bit sequence number
182  osMemcpy(aad, (uint8_t *) &espHeader->spi, 4);
183  STORE64BE(seq, aad + 4);
184  aadLen = 12;
185  }
186  else
187  {
188  //AAD Format with 32-bit sequence number
189  osMemcpy(aad, espHeader, 8);
190  aadLen = 8;
191  }
192 
193  //Initialize cipher context
194  error = cipherAlgo->init(&sa->cipherContext, sa->encKey, sa->encKeyLen);
195  //Any error to report?
196  if(error)
197  return error;
198 
199  //Authenticated decryption using CCM
200  error = ccmDecrypt(sa->cipherAlgo, &sa->cipherContext, nonce, 11, aad,
201  aadLen, data, payload, length, icv, sa->icvLen);
202  //Any error to report?
203  if(error)
204  return error;
205  }
206  else
207 #endif
208 #if (ESP_GCM_8_SUPPORT == ENABLED || ESP_GCM_12_SUPPORT == ENABLED || \
209  ESP_GCM_16_SUPPORT == ENABLED)
210  //GCM AEAD cipher?
211  if(sa->cipherMode == CIPHER_MODE_GCM)
212  {
213  size_t aadLen;
214  uint8_t aad[12];
215  uint8_t nonce[12];
216  GcmContext gcmContext;
217 
218  //The components of the nonce are the salt with the IV (refer to RFC 4106,
219  //section 4)
220  osMemcpy(nonce, sa->encKey + sa->encKeyLen, 4);
221  osMemcpy(nonce + 4, iv, 8);
222 
223  //Two formats of the AAD are defined (refer to RFC 4106, section 5)
224  if(sa->esn)
225  {
226  //Reconstruct the 64-bit sequence number
227  uint64_t seq = ipsecGetSeqNum(sa, ntohl(espHeader->seqNum));
228 
229  //AAD Format with 64-bit sequence number
230  osMemcpy(aad, (uint8_t *) &espHeader->spi, 4);
231  STORE64BE(seq, aad + 4);
232  aadLen = 12;
233  }
234  else
235  {
236  //AAD Format with 32-bit sequence number
237  osMemcpy(aad, espHeader, 8);
238  aadLen = 8;
239  }
240 
241  //Initialize cipher context
242  error = cipherAlgo->init(&sa->cipherContext, sa->encKey, sa->encKeyLen);
243  //Any error to report?
244  if(error)
245  return error;
246 
247  //Initialize GCM context
248  error = gcmInit(&gcmContext, sa->cipherAlgo, &sa->cipherContext);
249  //Any error to report?
250  if(error)
251  return error;
252 
253  //Authenticated decryption using GCM
254  error = gcmDecrypt(&gcmContext, nonce, 12, aad, aadLen, data, payload,
255  length, icv, sa->icvLen);
256  //Any error to report?
257  if(error)
258  return error;
259  }
260  else
261 #endif
262 #if (ESP_CHACHA20_POLY1305_SUPPORT == ENABLED)
263  //ChaCha20Poly1305 AEAD cipher?
264  if(sa->cipherMode == CIPHER_MODE_CHACHA20_POLY1305)
265  {
266  size_t aadLen;
267  uint8_t aad[12];
268  uint8_t nonce[12];
269 
270  //The 96-bit nonce is formed from a concatenation of the 32-bit salt and
271  //the 64-bit IV (refer to RFC 7634, section 2)
272  osMemcpy(nonce, sa->encKey + sa->encKeyLen, 4);
273  osMemcpy(nonce + 4, iv, 8);
274 
275  //Extended sequence numbers?
276  if(sa->esn)
277  {
278  //Reconstruct the 64-bit sequence number
279  uint64_t seq = ipsecGetSeqNum(sa, ntohl(espHeader->seqNum));
280 
281  //For SAs with ESN, the AAD is 12 octets: a 4-octet SPI followed by an
282  //8-octet sequence number as a 64-bit integer in big-endian byte order
283  //(refer to RFC 7634, section 2.1)
284  osMemcpy(aad, (uint8_t *) &espHeader->spi, 4);
285  STORE64BE(seq, aad + 4);
286  aadLen = 12;
287  }
288  else
289  {
290  //For SAs with 32-bit sequence numbers, the AAD is 8 octets: a 4-octet
291  //SPI followed by a 4-octet sequence number ordered exactly as it is in
292  //the packet
293  osMemcpy(aad, espHeader, 8);
294  aadLen = 8;
295  }
296 
297  //Authenticated decryption using ChaCha20Poly1305
298  error = chacha20Poly1305Decrypt(sa->encKey, sa->encKeyLen, nonce, 12,
299  aad, aadLen, data, payload, length, icv, sa->icvLen);
300  }
301  else
302 #endif
303  //Invalid cipher mode?
304  {
305  //The specified cipher mode is not supported
307  }
308 
309  //Point to the ESP trailer
310  length -= sizeof(EspTrailer);
311  espTrailer = (EspTrailer *) (payload + length);
312 
313  //The Pad Length field is the length of the Padding field
314  if(espTrailer->padLength > length)
316 
317  //The receiver should inspect the Padding field (refer to RFC 4303,
318  //section 2.4)
319  for(i = 0; i < espTrailer->padLength; i++)
320  {
321  //Padding bytes make up a monotonically increasing sequence
322  if(payload[length - espTrailer->padLength + i] != (i + 1))
324  }
325 
326  //Remove the padding prior to passing the decrypted data to the next layer
327  *payloadLen = length - espTrailer->padLength;
328 
329  //The Next Header field identifies the type of data contained in the
330  //payload data (refer to RFC 4303, section 2.6)
331  *nextHeader = espTrailer->nextHeader;
332 
333  //Successful processing
334  return NO_ERROR;
335 }
336 
337 
338 /**
339  * @brief Verify ICV checksum
340  * @param[in] context Pointer to the IPsec context
341  * @param[in] sa Pointer to the SAD entry
342  * @param[in] espHeader Pointer to the ESP header
343  * @param[in] payload Pointer to the payload data
344  * @param[in] length Length of the payload data, in bytes
345  * @param[in] icv Integrity Checksum Value (ICV)
346  * @return Error code
347  **/
348 
350  const EspHeader *espHeader, const uint8_t *payload, size_t length,
351  const uint8_t *icv)
352 {
353  error_t error;
354  size_t i;
355  uint8_t mask;
357 
358 #if (ESP_HMAC_SUPPORT == ENABLED)
359  //HMAC integrity algorithm?
360  if(sa->authHashAlgo != NULL)
361  {
362  HmacContext *hmacContext;
363 
364  //Point to the HMAC context
365  hmacContext = &context->hmacContext;
366 
367  //The SAD entry specifies the algorithms and keys to be employed for
368  //decryption and ICV computation (refer to RFC 4303, section 3.4.2)
369  error = hmacInit(hmacContext, sa->authHashAlgo, sa->authKey,
370  sa->authKeyLen);
371 
372  //Check status code
373  if(!error)
374  {
375  //The receiver computes the ICV over the ESP packet minus the ICV,
376  //using the specified integrity algorithm
377  hmacUpdate(hmacContext, espHeader, sizeof(EspHeader));
378  hmacUpdate(hmacContext, payload, length);
379 
380  //Extended sequence number?
381  if(sa->esn)
382  {
383  //Determine the higher-order bits of the sequence number
384  uint32_t seqh = ipsecGetSeqNum(sa, ntohl(espHeader->seqNum)) >> 32;
385 
386  //Convert the 32-bit value to network byte order
387  seqh = htonl(seqh);
388 
389  //The high-order 32 bits are maintained as part of the sequence
390  //number counter by both transmitter and receiver and are included
391  //in the computation of the ICV (refer to RFC 4303, section 2.2.1)
392  hmacUpdate(hmacContext, (uint8_t *) &seqh, 4);
393  }
394 
395  //Finalize HMAC computation
396  hmacFinal(hmacContext, checksum);
397  }
398  }
399  else
400 #endif
401 #if (ESP_CMAC_SUPPORT == ENABLED)
402  //CMAC integrity algorithm?
403  if(sa->authCipherAlgo != NULL)
404  {
405  CmacContext *cmacContext;
406 
407  //Point to the CMAC context
408  cmacContext = &context->cmacContext;
409 
410  //The SAD entry specifies the algorithms and keys to be employed for
411  //decryption and ICV computation (refer to RFC 4303, section 3.4.2)
412  error = cmacInit(cmacContext, sa->authCipherAlgo, sa->authKey,
413  sa->authKeyLen);
414 
415  //Check status code
416  if(!error)
417  {
418  //The receiver computes the ICV over the ESP packet minus the ICV,
419  //using the specified integrity algorithm
420  cmacUpdate(cmacContext, espHeader, sizeof(EspHeader));
421  cmacUpdate(cmacContext, payload, length);
422 
423  //Extended sequence number?
424  if(sa->esn)
425  {
426  //Determine the higher-order bits of the sequence number
427  uint32_t seqh = ipsecGetSeqNum(sa, ntohl(espHeader->seqNum)) >> 32;
428 
429  //Convert the 32-bit value to network byte order
430  seqh = htonl(seqh);
431 
432  //The high-order 32 bits are maintained as part of the sequence
433  //number counter by both transmitter and receiver and are included
434  //in the computation of the ICV (refer to RFC 4303, section 2.2.1)
435  cmacUpdate(cmacContext, (uint8_t *) &seqh, 4);
436  }
437 
438  //Finalize CMAC computation
439  cmacFinal(cmacContext, checksum, sa->icvLen);
440  }
441  }
442  else
443 #endif
444  //Unknown integrity algorithm?
445  {
446  //Report an error
447  error = ERROR_DECRYPTION_FAILED;
448  }
449 
450  //Check status code
451  if(!error)
452  {
453  //The computed ICV is bitwise compared to the received ICV
454  for(mask = 0, i = 0; i < sa->icvLen; i++)
455  {
456  mask |= checksum[i] ^ icv[i];
457  }
458 
459  //If the computed and received ICVs match, then the datagram is valid,
460  //and it is accepted (refer to RFC 4303, section 3.4.4.1)
461  error = (mask == 0) ? NO_ERROR : ERROR_DECRYPTION_FAILED;
462  }
463 
464  //Return status code
465  return error;
466 }
467 
468 #endif
uint8_t icv[]
Definition: ah.h:145
__weak_func error_t cbcDecrypt(const CipherAlgo *cipher, void *context, uint8_t *iv, const uint8_t *c, uint8_t *p, size_t length)
CBC decryption.
Definition: cbc.c:108
__weak_func error_t ccmDecrypt(const CipherAlgo *cipher, void *context, const uint8_t *n, size_t nLen, const uint8_t *a, size_t aLen, const uint8_t *c, uint8_t *p, size_t length, const uint8_t *t, size_t tLen)
Authenticated decryption using CCM.
Definition: ccm.c:208
error_t chacha20Poly1305Decrypt(const uint8_t *k, size_t kLen, const uint8_t *n, size_t nLen, const uint8_t *a, size_t aLen, const uint8_t *c, uint8_t *p, size_t length, const uint8_t *t, size_t tLen)
Authenticated decryption using ChaCha20Poly1305.
Collection of AEAD algorithms.
#define MAX_CIPHER_BLOCK_SIZE
Block cipher modes of operation.
error_t cmacFinal(CmacContext *context, uint8_t *mac, size_t macLen)
Finish the CMAC calculation.
Definition: cmac.c:237
void cmacUpdate(CmacContext *context, const void *data, size_t dataLen)
Update the CMAC context with a portion of the message being hashed.
Definition: cmac.c:191
error_t cmacInit(CmacContext *context, const CipherAlgo *cipher, const void *key, size_t keyLen)
Initialize CMAC calculation.
Definition: cmac.c:107
#define ntohl(value)
Definition: cpu_endian.h:422
#define htonl(value)
Definition: cpu_endian.h:414
#define STORE32BE(a, p)
Definition: cpu_endian.h:286
#define STORE64BE(a, p)
Definition: cpu_endian.h:322
@ CIPHER_MODE_CHACHA20_POLY1305
Definition: crypto.h:951
@ CIPHER_MODE_CCM
Definition: crypto.h:949
@ CIPHER_MODE_CBC
Definition: crypto.h:945
@ CIPHER_MODE_CTR
Definition: crypto.h:948
@ CIPHER_MODE_GCM
Definition: crypto.h:950
error_t ctrDecrypt(const CipherAlgo *cipher, void *context, uint_t m, uint8_t *t, const uint8_t *c, uint8_t *p, size_t length)
CTR decryption.
Definition: ctr.c:129
Debugging facilities.
error_t
Error codes.
Definition: error.h:43
@ ERROR_DECRYPTION_FAILED
Definition: error.h:241
@ NO_ERROR
Success.
Definition: error.h:44
@ ERROR_INVALID_PACKET
Definition: error.h:140
@ ERROR_UNSUPPORTED_CIPHER_MODE
Definition: error.h:128
ESP (IP Encapsulating Security Payload)
EspHeader
Definition: esp.h:255
EspTrailer
Definition: esp.h:267
error_t espVerifyChecksum(IpsecContext *context, IpsecSadEntry *sa, const EspHeader *espHeader, const uint8_t *payload, size_t length, const uint8_t *icv)
Verify ICV checksum.
error_t espDecryptPacket(IpsecContext *context, IpsecSadEntry *sa, const EspHeader *espHeader, uint8_t *payload, size_t *payloadLen, uint8_t *nextHeader)
Decrypt an incoming ESP packet.
ESP packet decryption.
uint8_t data[]
Definition: ethernet.h:222
__weak_func error_t gcmInit(GcmContext *context, const CipherAlgo *cipherAlgo, void *cipherContext)
Initialize GCM context.
Definition: gcm.c:99
__weak_func error_t gcmDecrypt(GcmContext *context, const uint8_t *iv, size_t ivLen, const uint8_t *a, size_t aLen, const uint8_t *c, uint8_t *p, size_t length, const uint8_t *t, size_t tLen)
Authenticated decryption using GCM.
Definition: gcm.c:361
#define MAX_HASH_DIGEST_SIZE
__weak_func error_t hmacInit(HmacContext *context, const HashAlgo *hash, const void *key, size_t keyLen)
Initialize HMAC calculation.
Definition: hmac.c:140
__weak_func void hmacFinal(HmacContext *context, uint8_t *digest)
Finish the HMAC calculation.
Definition: hmac.c:218
__weak_func void hmacUpdate(HmacContext *context, const void *data, size_t length)
Update the HMAC context with a portion of the message being hashed.
Definition: hmac.c:201
uint8_t iv[]
Definition: ike.h:1502
IPsec (IP security)
#define IpsecSadEntry
Definition: ipsec.h:36
uint64_t ipsecGetSeqNum(IpsecSadEntry *sa, uint32_t seql)
Determine the higher-order bits of the sequence number.
IPsec processing of inbound IP traffic.
uint8_t payload[]
Definition: ipv6.h:277
uint8_t nextHeader
Definition: ipv6.h:273
uint16_t payloadLen
Definition: ipv6.h:272
#define osMemcpy(dest, src, length)
Definition: os_port.h:141
Common interface for encryption algorithms.
Definition: crypto.h:1036
size_t blockSize
Definition: crypto.h:1040
CipherAlgoInit init
Definition: crypto.h:1041
CMAC algorithm context.
Definition: cmac.h:54
GCM context.
Definition: gcm.h:64
const CipherAlgo * cipherAlgo
Cipher algorithm.
Definition: gcm.h:65
HMAC algorithm context.
Definition: hmac.h:59
IPsec context.
Definition: ipsec.h:434
CmacContext cmacContext
CMAC context.
Definition: ipsec.h:444
uint8_t buffer[ESP_BUFFER_SIZE]
Memory buffer for input/output operations.
Definition: ipsec.h:450
HmacContext hmacContext
HMAC context.
Definition: ipsec.h:447
uint8_t length
Definition: tcp.h:368
uint16_t checksum
Definition: tcp.h:355
uint8_t mask
Definition: web_socket.h:319