esp.c
Go to the documentation of this file.
1 /**
2  * @file esp.c
3  * @brief ESP (IP Encapsulating Security Payload)
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.4
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"
38 #include "ipsec/ipsec_misc.h"
39 #include "esp/esp.h"
40 #include "esp/esp_packet_decrypt.h"
41 #include "core/tcp_fsm.h"
42 #include "core/raw_socket.h"
43 #include "ipv4/icmp.h"
44 #include "debug.h"
45 
46 //Check IPsec library configuration
47 #if (ESP_SUPPORT == ENABLED)
48 
49 
50 /**
51  * @brief Process ESP protected packet
52  * @param[in] interface Underlying network interface
53  * @param[in] ipv4Header Pointer to the IPv4 header
54  * @param[in] buffer Multi-part buffer containing the ESP protected packet
55  * @param[in] offset Offset to the first byte of the ESP header
56  * @param[in] ancillary Additional options passed to the stack along with
57  * the packet
58  * @return Error code
59  **/
60 
62  const Ipv4Header *ipv4Header, const NetBuffer *buffer, size_t offset,
63  NetRxAncillary *ancillary)
64 {
65  error_t error;
66  size_t length;
67  uint64_t seq;
68  uint8_t nextHeader;
69  size_t offset2;
70  NetBuffer *buffer2;
71  IpsecContext *context;
72  IpsecSadEntry *sa;
73  EspHeader *espHeader;
74  IpsecSelector selector;
75  IpPseudoHeader pseudoHeader;
76 
77  //Point to the IPsec context
78  context = netContext.ipsecContext;
79  //Sanity check
80  if(context == NULL)
81  return ERROR_FAILURE;
82 
83  //Retrieve the length of the payload
84  length = netBufferGetLength(buffer) - offset;
85 
86  //Malformed packet?
87  if(length < sizeof(EspHeader))
88  return ERROR_INVALID_HEADER;
89 
90  //Point to the ESP header
91  espHeader = netBufferAt(buffer, offset, 0);
92  //Sanity check
93  if(espHeader == NULL)
94  return ERROR_FAILURE;
95 
96  //Debug message
97  TRACE_INFO("Parsing ESP header...\r\n");
98  //Dump AH header contents for debugging purpose
99  espDumpHeader(espHeader);
100 
101  //Upon receipt of a packet containing an ESP Header, the receiver determines
102  //the appropriate (unidirectional) SA via lookup in the SAD (refer to
103  //RFC 4303, section 3.4.2)
105  ntohl(espHeader->spi));
106 
107  //If no valid Security Association exists for this packet the receiver
108  //must discard the packet. This is an auditable event
109  if(sa == NULL)
110  {
111  //Debug message
112  TRACE_WARNING("ESP: No matching SA found!\r\n");
113  //Report an error
114  return ERROR_POLICY_FAILURE;
115  }
116 
117  //Check IPsec mode
118  if(sa->mode == IPSEC_MODE_TRANSPORT)
119  {
120  //Transport mode ESP is applied only to whole IP datagrams (not to IP
121  //fragments)
122  if((ntohs(ipv4Header->fragmentOffset) & IPV4_OFFSET_MASK) != 0 ||
123  (ntohs(ipv4Header->fragmentOffset) & IPV4_FLAG_MF) != 0)
124  {
125  return ERROR_INVALID_HEADER;
126  }
127  }
128  else
129  {
130  //In tunnel mode, ESP is applied to an IP packet, which may be a fragment
131  //of an IP datagram
132  }
133 
134  //Because only the low-order 32 bits are transmitted with the packet, the
135  //receiver must deduce and track the sequence number subspace into which
136  //each packet falls
137  seq = ipsecGetSeqNum(sa, ntohl(espHeader->seqNum));
138 
139  //For each received packet, the receiver must verify that the packet
140  //contains a Sequence Number that does not duplicate the Sequence Number of
141  //any other packets received during the life of this SA. This should be the
142  //first ESP check applied to a packet after it has been matched to an SA, to
143  //speed rejection of duplicate packets (refer to RFC 4303, section 3.4.3)
144  error = ipsecCheckReplayWindow(sa, seq);
145 
146  //Duplicate packets are rejected
147  if(error)
148  {
149  //Debug message
150  TRACE_WARNING("ESP: Invalid sequence number!\r\n");
151  //Report an error
153  }
154 
155  //Point to the payload data
156  offset += sizeof(EspHeader);
157  length -= sizeof(EspHeader);
158 
159  //Copy the payload data to be decrypted
160  netBufferRead(context->buffer, buffer, offset, length);
161 
162  //if a separate integrity algorithm is employed, then the receiver proceeds
163  //to integrity verification, then decryption. If a combined mode algorithm
164  //is employed, the integrity check is performed along with decryption
165  error = espDecryptPacket(context, sa, espHeader, context->buffer, &length,
166  &nextHeader);
167 
168  //If the integrity check fails, the receiver must discard the received IP
169  //datagram as invalid. This is an auditable event
170  if(error)
171  {
172  //Debug message
173  TRACE_WARNING("ESP: ICV validation failed!\r\n");
174  //Report an error
176  }
177 
178  //The receive window is updated only if the ICV verification succeeds
179  ipsecUpdateReplayWindow(sa, seq);
180 
181  //Allocate a buffer to hold the decrypted payload
182  buffer2 = ipAllocBuffer(length, &offset2);
183  //Failed to allocate memory?
184  if(buffer2 == NULL)
185  return ERROR_OUT_OF_MEMORY;
186 
187  //Copy the resulting data
188  netBufferWrite(buffer2, offset2, context->buffer, length);
189 
190  //Retrieve packet's selector
191  error = ipsecGetInboundIpv4PacketSelector(ipv4Header, nextHeader, buffer2,
192  offset2, &selector);
193 
194  //Check status code
195  if(!error)
196  {
197  //Match the packet against the inbound selectors identified by the SAD
198  //entry to verify that the received packet is appropriate for the SA via
199  //which it was received (refer to RFC 4301, section 5.2)
200  if(ipsecIsSubsetSelector(&selector, &sa->selector))
201  {
202  //Form the IPv4 pseudo header
203  pseudoHeader.length = sizeof(Ipv4PseudoHeader);
204  pseudoHeader.ipv4Data.srcAddr = ipv4Header->srcAddr;
205  pseudoHeader.ipv4Data.destAddr = ipv4Header->destAddr;
206  pseudoHeader.ipv4Data.reserved = 0;
207  pseudoHeader.ipv4Data.protocol = nextHeader;
208  pseudoHeader.ipv4Data.length = htons(length);
209 
210  //If the computed and received ICVs match, then the datagram is valid,
211  //and it is accepted (refer to RFC 4303, section 3.4.4.1)
212  switch(nextHeader)
213  {
214  //ICMP protocol?
215  case IPV4_PROTOCOL_ICMP:
216  //Process incoming ICMP message
217  icmpProcessMessage(interface, &pseudoHeader.ipv4Data, buffer2,
218  offset2);
219 
220 #if (RAW_SOCKET_SUPPORT == ENABLED)
221  //Allow raw sockets to process ICMP messages
222  rawSocketProcessIpPacket(interface, &pseudoHeader, buffer2,
223  offset2, ancillary);
224 #endif
225  //Continue processing
226  break;
227 
228 #if (IGMP_HOST_SUPPORT == ENABLED || IGMP_ROUTER_SUPPORT == ENABLED || \
229  IGMP_SNOOPING_SUPPORT == ENABLED)
230  //IGMP protocol?
231  case IPV4_PROTOCOL_IGMP:
232  //Process incoming IGMP message
233  igmpProcessMessage(interface, &pseudoHeader.ipv4Data, buffer2,
234  offset2, ancillary);
235 
236 #if (RAW_SOCKET_SUPPORT == ENABLED)
237  //Allow raw sockets to process IGMP messages
238  rawSocketProcessIpPacket(interface, &pseudoHeader, buffer2,
239  offset2, ancillary);
240 #endif
241  //Continue processing
242  break;
243 #endif
244 
245 #if (TCP_SUPPORT == ENABLED)
246  //TCP protocol?
247  case IPV4_PROTOCOL_TCP:
248  //Process incoming TCP segment
249  tcpProcessSegment(interface, &pseudoHeader, buffer2, offset2,
250  ancillary);
251  //Continue processing
252  break;
253 #endif
254 
255 #if (UDP_SUPPORT == ENABLED)
256  //UDP protocol?
257  case IPV4_PROTOCOL_UDP:
258  //Process incoming UDP datagram
259  error = udpProcessDatagram(interface, &pseudoHeader, buffer2, offset2,
260  ancillary);
261  //Continue processing
262  break;
263 #endif
264 
265  //Unknown protocol?
266  default:
267 #if (RAW_SOCKET_SUPPORT == ENABLED)
268  //Allow raw sockets to process IPv4 packets
269  error = rawSocketProcessIpPacket(interface, &pseudoHeader, buffer2,
270  offset2, ancillary);
271 #else
272  //Report an error
274 #endif
275  //Continue processing
276  break;
277  }
278  }
279  else
280  {
281  //If an IPsec system receives an inbound packet on an SA and the
282  //packet's header fields are not consistent with the selectors for
283  //the SA, it must discard the packet. This is an auditable event
284  error = ERROR_POLICY_FAILURE;
285  }
286  }
287 
288  //Free previously allocated memory
289  netBufferFree(buffer2);
290 
291  //Return status code
292  return error;
293 }
294 
295 
296 /**
297  * @brief Dump ESP header for debugging purpose
298  * @param[in] espHeader Pointer to the ESP header
299  **/
300 
301 void espDumpHeader(const EspHeader *espHeader)
302 {
303  //Dump ESP header contents
304  TRACE_DEBUG(" SPI = 0x%08" PRIX32 "\r\n", ntohl(espHeader->spi));
305  TRACE_DEBUG(" Sequence Number = 0x%08" PRIX32 "\r\n", ntohl(espHeader->seqNum));
306 }
307 
308 #endif
#define htons(value)
Definition: cpu_endian.h:413
NetBuffer * ipAllocBuffer(size_t length, size_t *offset)
Allocate a buffer to hold an IP packet.
Definition: ip.c:711
#define Ipv4Header
Definition: ipv4.h:36
@ IPV4_PROTOCOL_ICMP
Definition: ipv4.h:250
@ IPV4_OFFSET_MASK
Definition: ipv4.h:240
@ ERROR_WRONG_SEQUENCE_NUMBER
Definition: error.h:182
error_t rawSocketProcessIpPacket(NetInterface *interface, const IpPseudoHeader *pseudoHeader, const NetBuffer *buffer, size_t offset, const NetRxAncillary *ancillary)
Process incoming IP packet.
Definition: raw_socket.c:68
IPsec selector.
Definition: ipsec.h:302
size_t netBufferRead(void *dest, const NetBuffer *src, size_t srcOffset, size_t length)
Read data from a multi-part buffer.
Definition: net_mem.c:690
Structure describing a buffer that spans multiple chunks.
Definition: net_mem.h:89
@ ERROR_INVALID_HEADER
Definition: error.h:87
ESP packet decryption.
@ ERROR_OUT_OF_MEMORY
Definition: error.h:63
NetContext netContext
Definition: net.c:74
error_t udpProcessDatagram(NetInterface *interface, const IpPseudoHeader *pseudoHeader, const NetBuffer *buffer, size_t offset, const NetRxAncillary *ancillary)
Incoming UDP datagram processing.
Definition: udp.c:124
size_t length
Definition: ip.h:111
error_t ipsecCheckReplayWindow(const IpsecSadEntry *sa, uint64_t seqNum)
Perform replay detection.
@ IPSEC_PROTOCOL_ESP
Definition: ipsec.h:193
uint64_t ipsecGetSeqNum(IpsecSadEntry *sa, uint32_t seql)
Determine the higher-order bits of the sequence number.
IP pseudo header.
Definition: ip.h:110
void icmpProcessMessage(NetInterface *interface, const Ipv4PseudoHeader *requestPseudoHeader, const NetBuffer *buffer, size_t offset)
Incoming ICMP message processing.
Definition: icmp.c:111
@ IPV4_PROTOCOL_TCP
Definition: ipv4.h:252
ESP (IP Encapsulating Security Payload)
ICMP (Internet Control Message Protocol)
@ IPSEC_MODE_TRANSPORT
Definition: ipsec.h:205
error_t
Error codes.
Definition: error.h:43
@ ERROR_PROTOCOL_UNREACHABLE
Definition: error.h:84
TCP finite state machine.
@ ERROR_FAILURE
Generic error code.
Definition: error.h:45
@ IPV4_FLAG_MF
Definition: ipv4.h:239
Helper routines for IPsec.
bool_t ipsecIsSubsetSelector(const IpsecSelector *selector1, const IpsecSelector *selector2)
Test if a selector is a subset of another selector.
Definition: ipsec_misc.c:362
#define NetRxAncillary
Definition: net_misc.h:40
#define NetInterface
Definition: net.h:36
void netBufferFree(NetBuffer *buffer)
Dispose a multi-part buffer.
Definition: net_mem.c:282
uint8_t nextHeader
Definition: ipv6.h:282
IPsec context.
Definition: ipsec.h:434
#define Ipv4PseudoHeader
Definition: ipv4.h:39
#define TRACE_INFO(...)
Definition: debug.h:95
uint8_t length
Definition: tcp.h:368
size_t netBufferGetLength(const NetBuffer *buffer)
Get the actual length of a multi-part buffer.
Definition: net_mem.c:297
IPsec processing of inbound IP traffic.
IpsecSadEntry * ipsecFindInboundSadEntry(IpsecContext *context, IpsecProtocol protocol, uint32_t spi)
Search the SAD database for a matching inbound entry.
Definition: ipsec_misc.c:134
Anti-replay mechanism.
void * ipsecContext
IPsec context.
Definition: net.h:333
#define IpsecSadEntry
Definition: ipsec.h:36
TCP/IP raw sockets.
@ IPV4_PROTOCOL_IGMP
Definition: ipv4.h:251
EspHeader
Definition: esp.h:255
#define ntohs(value)
Definition: cpu_endian.h:421
#define TRACE_WARNING(...)
Definition: debug.h:85
#define TRACE_DEBUG(...)
Definition: debug.h:107
IPsec (IP security)
@ IPV4_PROTOCOL_UDP
Definition: ipv4.h:253
@ ERROR_AUTHENTICATION_FAILED
Definition: error.h:69
error_t ipv4ProcessEspHeader(NetInterface *interface, const Ipv4Header *ipv4Header, const NetBuffer *buffer, size_t offset, NetRxAncillary *ancillary)
Process ESP protected packet.
Definition: esp.c:61
error_t espDecryptPacket(IpsecContext *context, IpsecSadEntry *sa, const EspHeader *espHeader, uint8_t *payload, size_t *payloadLen, uint8_t *nextHeader)
Decrypt an incoming ESP packet.
size_t netBufferWrite(NetBuffer *dest, size_t destOffset, const void *src, size_t length)
Write data to a multi-part buffer.
Definition: net_mem.c:637
void * netBufferAt(const NetBuffer *buffer, size_t offset, size_t length)
Returns a pointer to a data segment.
Definition: net_mem.c:418
error_t ipsecGetInboundIpv4PacketSelector(const Ipv4Header *ipv4Header, uint8_t nextHeader, const NetBuffer *buffer, size_t offset, IpsecSelector *selector)
Extract packet's selector from inbound IPv4 packet.
void tcpProcessSegment(NetInterface *interface, const IpPseudoHeader *pseudoHeader, const NetBuffer *buffer, size_t offset, const NetRxAncillary *ancillary)
Incoming TCP segment processing.
Definition: tcp_fsm.c:73
void ipsecUpdateReplayWindow(IpsecSadEntry *sa, uint64_t seqNum)
Update sliding window.
void espDumpHeader(const EspHeader *espHeader)
Dump ESP header for debugging purpose.
Definition: esp.c:301
@ ERROR_POLICY_FAILURE
Definition: error.h:299
#define ntohl(value)
Definition: cpu_endian.h:422
Ipv4PseudoHeader ipv4Data
Definition: ip.h:115
uint8_t buffer[ESP_BUFFER_SIZE]
Memory buffer for input/output operations.
Definition: ipsec.h:450
void igmpProcessMessage(NetInterface *interface, const Ipv4PseudoHeader *pseudoHeader, const NetBuffer *buffer, size_t offset, const NetRxAncillary *ancillary)
Process incoming IGMP message.
Definition: igmp_common.c:292
Debugging facilities.