2 The implementation of IPsec.
4 (C) Copyright 2015 Hewlett-Packard Development Company, L.P.<BR>
5 Copyright (c) 2009 - 2018, Intel Corporation. All rights reserved.<BR>
7 This program and the accompanying materials
8 are licensed and made available under the terms and conditions of the BSD License
9 which accompanies this distribution. The full text of the license may be found at
10 http://opensource.org/licenses/bsd-license.php.
12 THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
13 WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
17 #include "IpSecImpl.h"
18 #include "IkeService.h"
19 #include "IpSecDebug.h"
20 #include "IpSecCryptIo.h"
21 #include "IpSecConfigImpl.h"
24 Check if the specified Address is the Valid Address Range.
26 This function checks if the bytes after prefixed length are all Zero in this
27 Address. This Address is supposed to point to a range address. That means it
28 should gives the correct prefixed address and the bytes outside the prefixed are
31 @param[in] IpVersion The IP version.
32 @param[in] Address Points to EFI_IP_ADDRESS to be checked.
33 @param[in] PrefixLength The PrefixeLength of this address.
35 @retval TRUE The address is a vaild address range.
36 @retval FALSE The address is not a vaild address range.
40 IpSecValidAddressRange (
42 IN EFI_IP_ADDRESS
*Address
,
51 EFI_IP_ADDRESS ZeroAddr
;
53 if (PrefixLength
== 0) {
57 AddrLen
= (UINT8
) ((IpVersion
== IP_VERSION_4
) ? 32 : 128);
59 if (AddrLen
<= PrefixLength
) {
63 Div
= (UINT8
) (PrefixLength
/ 8);
64 Mod
= (UINT8
) (PrefixLength
% 8);
65 Addr
= (UINT8
*) Address
;
66 ZeroMem (&ZeroAddr
, sizeof (EFI_IP_ADDRESS
));
69 // Check whether the mod part of host scope is zero or not.
72 Mask
= (UINT8
) (0xFF << (8 - Mod
));
74 if ((Addr
[Div
] | Mask
) != Mask
) {
81 // Check whether the div part of host scope is zero or not.
86 sizeof (EFI_IP_ADDRESS
) - Div
95 Extrct the Address Range from a Address.
97 This function keep the prefix address and zero other part address.
99 @param[in] Address Point to a specified address.
100 @param[in] PrefixLength The prefix length.
101 @param[out] Range Contain the return Address Range.
105 IpSecExtractAddressRange (
106 IN EFI_IP_ADDRESS
*Address
,
107 IN UINT8 PrefixLength
,
108 OUT EFI_IP_ADDRESS
*Range
116 if (PrefixLength
== 0) {
120 Div
= (UINT8
) (PrefixLength
/ 8);
121 Mod
= (UINT8
) (PrefixLength
% 8);
122 Addr
= (UINT8
*) Range
;
124 CopyMem (Range
, Address
, sizeof (EFI_IP_ADDRESS
));
127 // Zero the mod part of host scope.
130 Mask
= (UINT8
) (0xFF << (8 - Mod
));
131 Addr
[Div
] = (UINT8
) (Addr
[Div
] & Mask
);
135 // Zero the div part of host scope.
137 ZeroMem (&Addr
[Div
], sizeof (EFI_IP_ADDRESS
) - Div
);
142 Checks if the IP Address in the address range of AddressInfos specified.
144 @param[in] IpVersion The IP version.
145 @param[in] IpAddr Point to EFI_IP_ADDRESS to be check.
146 @param[in] AddressInfo A list of EFI_IP_ADDRESS_INFO that is used to check
147 the IP Address is matched.
148 @param[in] AddressCount The total numbers of the AddressInfo.
150 @retval TRUE If the Specified IP Address is in the range of the AddressInfos specified.
151 @retval FALSE If the Specified IP Address is not in the range of the AddressInfos specified.
155 IpSecMatchIpAddress (
157 IN EFI_IP_ADDRESS
*IpAddr
,
158 IN EFI_IP_ADDRESS_INFO
*AddressInfo
,
159 IN UINT32 AddressCount
162 EFI_IP_ADDRESS Range
;
168 for (Index
= 0; Index
< AddressCount
; Index
++) {
170 // Check whether the target address is in the address range
171 // if it's a valid range of address.
173 if (IpSecValidAddressRange (
175 &AddressInfo
[Index
].Address
,
176 AddressInfo
[Index
].PrefixLength
179 // Get the range of the target address belongs to.
181 ZeroMem (&Range
, sizeof (EFI_IP_ADDRESS
));
182 IpSecExtractAddressRange (
184 AddressInfo
[Index
].PrefixLength
,
190 &AddressInfo
[Index
].Address
,
191 sizeof (EFI_IP_ADDRESS
)
194 // The target address is in the address range.
203 &AddressInfo
[Index
].Address
,
204 sizeof (EFI_IP_ADDRESS
)
207 // The target address is exact same as the address.
217 Check if the specified Protocol and Prot is supported by the specified SPD Entry.
219 This function is the subfunction of IPsecLookUpSpdEntry() that is used to
220 check if the sent/received IKE packet has the related SPD entry support.
222 @param[in] Protocol The Protocol to be checked.
223 @param[in] IpPayload Point to IP Payload to be check.
224 @param[in] SpdProtocol The Protocol supported by SPD.
225 @param[in] SpdLocalPort The Local Port in SPD.
226 @param[in] SpdRemotePort The Remote Port in SPD.
227 @param[in] IsOutbound Flag to indicate the is for IKE Packet sending or recieving.
229 @retval TRUE The Protocol and Port are supported by the SPD Entry.
230 @retval FALSE The Protocol and Port are not supported by the SPD Entry.
234 IpSecMatchNextLayerProtocol (
237 IN UINT16 SpdProtocol
,
238 IN UINT16 SpdLocalPort
,
239 IN UINT16 SpdRemotePort
,
240 IN BOOLEAN IsOutbound
245 if (SpdProtocol
== EFI_IPSEC_ANY_PROTOCOL
) {
251 if (SpdProtocol
== Protocol
) {
253 case EFI_IP_PROTO_UDP
:
254 case EFI_IP_PROTO_TCP
:
256 // For udp and tcp, (0, 0) means no need to check local and remote
257 // port. The payload is passed from upper level, which means it should
258 // be in network order.
260 IsMatch
= (BOOLEAN
) (SpdLocalPort
== 0 && SpdRemotePort
== 0);
261 IsMatch
= (BOOLEAN
) (IsMatch
||
264 NTOHS (((EFI_UDP_HEADER
*) IpPayload
)->SrcPort
) == SpdLocalPort
&&
265 NTOHS (((EFI_UDP_HEADER
*) IpPayload
)->DstPort
) == SpdRemotePort
269 IsMatch
= (BOOLEAN
) (IsMatch
||
272 NTOHS (((EFI_UDP_HEADER
*) IpPayload
)->DstPort
) == SpdLocalPort
&&
273 NTOHS (((EFI_UDP_HEADER
*) IpPayload
)->SrcPort
) == SpdRemotePort
278 case EFI_IP_PROTO_ICMP
:
280 // For icmpv4, type code is replaced with local port and remote port,
281 // and (0, 0) means no need to check.
283 IsMatch
= (BOOLEAN
) (SpdLocalPort
== 0 && SpdRemotePort
== 0);
284 IsMatch
= (BOOLEAN
) (IsMatch
||
285 (BOOLEAN
) (((IP4_ICMP_HEAD
*) IpPayload
)->Type
== SpdLocalPort
&&
286 ((IP4_ICMP_HEAD
*) IpPayload
)->Code
== SpdRemotePort
293 // For icmpv6, type code is replaced with local port and remote port,
294 // and (0, 0) means no need to check.
296 IsMatch
= (BOOLEAN
) (SpdLocalPort
== 0 && SpdRemotePort
== 0);
298 IsMatch
= (BOOLEAN
) (IsMatch
||
299 (BOOLEAN
) (((IP6_ICMP_HEAD
*) IpPayload
)->Type
== SpdLocalPort
&&
300 ((IP6_ICMP_HEAD
*) IpPayload
)->Code
== SpdRemotePort
315 Find the SAD through a specified SPD's SAD list.
317 @param[in] SadList SAD list related to a specified SPD entry.
318 @param[in] DestAddress The destination address used to find the SAD entry.
319 @param[in] IpVersion The IP version. Ip4 or Ip6.
321 @return The pointer to a certain SAD entry.
325 IpSecLookupSadBySpd (
326 IN LIST_ENTRY
*SadList
,
327 IN EFI_IP_ADDRESS
*DestAddress
,
332 IPSEC_SAD_ENTRY
*SadEntry
;
334 NET_LIST_FOR_EACH (Entry
, SadList
) {
336 SadEntry
= IPSEC_SAD_ENTRY_FROM_SPD (Entry
);
338 // Find the right SAD entry which contains the appointed dest address.
340 if (IpSecMatchIpAddress (
343 SadEntry
->Data
->SpdSelector
->RemoteAddress
,
344 SadEntry
->Data
->SpdSelector
->RemoteAddressCount
354 Find the SAD through whole SAD list.
356 @param[in] Spi The SPI used to search the SAD entry.
357 @param[in] DestAddress The destination used to search the SAD entry.
358 @param[in] IpVersion The IP version. Ip4 or Ip6.
360 @return the pointer to a certain SAD entry.
364 IpSecLookupSadBySpi (
366 IN EFI_IP_ADDRESS
*DestAddress
,
372 IPSEC_SAD_ENTRY
*SadEntry
;
374 SadList
= &mConfigData
[IPsecConfigDataTypeSad
];
376 NET_LIST_FOR_EACH (Entry
, SadList
) {
378 SadEntry
= IPSEC_SAD_ENTRY_FROM_LIST (Entry
);
381 // Find the right SAD entry which contain the appointed spi and dest addr.
383 if (SadEntry
->Id
->Spi
== Spi
) {
384 if (SadEntry
->Data
->Mode
== EfiIPsecTunnel
) {
387 &SadEntry
->Data
->TunnelDestAddress
,
388 sizeof (EFI_IP_ADDRESS
)
393 if (SadEntry
->Data
->SpdSelector
!= NULL
&&
394 IpSecMatchIpAddress (
397 SadEntry
->Data
->SpdSelector
->RemoteAddress
,
398 SadEntry
->Data
->SpdSelector
->RemoteAddressCount
410 Look up if there is existing SAD entry for specified IP packet sending.
412 This function is called by the IPsecProcess when there is some IP packet needed to
413 send out. This function checks if there is an existing SAD entry that can be serviced
414 to this IP packet sending. If no existing SAD entry could be used, this
415 function will invoke an IPsec Key Exchange Negotiation.
417 @param[in] Private Points to private data.
418 @param[in] NicHandle Points to a NIC handle.
419 @param[in] IpVersion The version of IP.
420 @param[in] IpHead The IP Header of packet to be sent out.
421 @param[in] IpPayload The IP Payload to be sent out.
422 @param[in] OldLastHead The Last protocol of the IP packet.
423 @param[in] SpdEntry Points to a related SPD entry.
424 @param[out] SadEntry Contains the Point of a related SAD entry.
426 @retval EFI_DEVICE_ERROR One of following conditions is TRUE:
427 - If don't find related UDP service.
428 - Sequence Number is used up.
429 - Extension Sequence Number is used up.
430 @retval EFI_NOT_READY No existing SAD entry could be used.
431 @retval EFI_SUCCESS Find the related SAD entry.
435 IpSecLookupSadEntry (
436 IN IPSEC_PRIVATE_DATA
*Private
,
437 IN EFI_HANDLE NicHandle
,
441 IN UINT8 OldLastHead
,
442 IN IPSEC_SPD_ENTRY
*SpdEntry
,
443 OUT IPSEC_SAD_ENTRY
**SadEntry
446 IKE_UDP_SERVICE
*UdpService
;
447 IPSEC_SAD_ENTRY
*Entry
;
448 IPSEC_SAD_DATA
*Data
;
449 EFI_IP_ADDRESS DestIp
;
453 UdpService
= IkeLookupUdp (Private
, NicHandle
, IpVersion
);
455 if (UdpService
== NULL
) {
456 return EFI_DEVICE_ERROR
;
459 // Parse the destination address from ip header.
461 ZeroMem (&DestIp
, sizeof (EFI_IP_ADDRESS
));
462 if (IpVersion
== IP_VERSION_4
) {
465 &((IP4_HEAD
*) IpHead
)->Dst
,
471 &((EFI_IP6_HEADER
*) IpHead
)->DestinationAddress
,
472 sizeof (EFI_IP_ADDRESS
)
477 // Find the SAD entry in the spd.sas list according to the dest address.
479 Entry
= IpSecLookupSadBySpd (&SpdEntry
->Data
->Sas
, &DestIp
, IpVersion
);
482 if (OldLastHead
!= IP6_ICMP
||
483 (OldLastHead
== IP6_ICMP
&& *IpPayload
== ICMP_V6_ECHO_REQUEST
)
486 // Start ike negotiation process except the request packet of ping.
488 if (SpdEntry
->Data
->ProcessingPolicy
->Mode
== EfiIPsecTunnel
) {
492 &SpdEntry
->Data
->ProcessingPolicy
->TunnelOption
->RemoteTunnelAddress
504 return EFI_NOT_READY
;
509 if (!Data
->ManualSet
) {
510 if (Data
->ESNEnabled
) {
512 // Validate the 64bit sn number if 64bit sn enabled.
514 if ((UINT64
) (Data
->SequenceNumber
+ 1) == 0) {
516 // TODO: Re-negotiate SA
518 return EFI_DEVICE_ERROR
;
522 // Validate the 32bit sn number if 64bit sn disabled.
524 SeqNum32
= (UINT32
) Data
->SequenceNumber
;
525 if ((UINT32
) (SeqNum32
+ 1) == 0) {
527 // TODO: Re-negotiate SA
529 return EFI_DEVICE_ERROR
;
540 Find a PAD entry according to a remote IP address.
542 @param[in] IpVersion The version of IP.
543 @param[in] IpAddr Points to remote IP address.
545 @return the pointer of related PAD entry.
549 IpSecLookupPadEntry (
551 IN EFI_IP_ADDRESS
*IpAddr
556 EFI_IP_ADDRESS_INFO
*IpAddrInfo
;
557 IPSEC_PAD_ENTRY
*PadEntry
;
559 PadList
= &mConfigData
[IPsecConfigDataTypePad
];
561 for (Entry
= PadList
->ForwardLink
; Entry
!= PadList
; Entry
= Entry
->ForwardLink
) {
563 PadEntry
= IPSEC_PAD_ENTRY_FROM_LIST (Entry
);
564 IpAddrInfo
= &PadEntry
->Id
->Id
.IpAddress
;
566 // Find the right pad entry which contain the appointed dest addr.
568 if (IpSecMatchIpAddress (IpVersion
, IpAddr
, IpAddrInfo
, 1)) {
577 Check if the specified IP packet can be serviced by this SPD entry.
579 @param[in] SpdEntry Point to SPD entry.
580 @param[in] IpVersion Version of IP.
581 @param[in] IpHead Point to IP header.
582 @param[in] IpPayload Point to IP payload.
583 @param[in] Protocol The Last protocol of IP packet.
584 @param[in] IsOutbound Traffic direction.
585 @param[out] Action The support action of SPD entry.
587 @retval EFI_SUCCESS Find the related SPD.
588 @retval EFI_NOT_FOUND Not find the related SPD entry;
592 IpSecLookupSpdEntry (
593 IN IPSEC_SPD_ENTRY
*SpdEntry
,
598 IN BOOLEAN IsOutbound
,
599 OUT EFI_IPSEC_ACTION
*Action
602 EFI_IPSEC_SPD_SELECTOR
*SpdSel
;
605 EFI_IP_ADDRESS SrcAddr
;
606 EFI_IP_ADDRESS DstAddr
;
609 ASSERT (SpdEntry
!= NULL
);
610 SpdSel
= SpdEntry
->Selector
;
611 Ip4
= (IP4_HEAD
*) IpHead
;
612 Ip6
= (EFI_IP6_HEADER
*) IpHead
;
614 ZeroMem (&SrcAddr
, sizeof (EFI_IP_ADDRESS
));
615 ZeroMem (&DstAddr
, sizeof (EFI_IP_ADDRESS
));
618 // Parse the source and destination address from ip header.
620 if (IpVersion
== IP_VERSION_4
) {
621 CopyMem (&SrcAddr
, &Ip4
->Src
, sizeof (IP4_ADDR
));
622 CopyMem (&DstAddr
, &Ip4
->Dst
, sizeof (IP4_ADDR
));
624 CopyMem (&SrcAddr
, &Ip6
->SourceAddress
, sizeof (EFI_IPv6_ADDRESS
));
625 CopyMem (&DstAddr
, &Ip6
->DestinationAddress
, sizeof (EFI_IPv6_ADDRESS
));
628 // Check the local and remote addresses for outbound traffic
630 SpdMatch
= (BOOLEAN
)(IsOutbound
&&
631 IpSecMatchIpAddress (
634 SpdSel
->LocalAddress
,
635 SpdSel
->LocalAddressCount
637 IpSecMatchIpAddress (
640 SpdSel
->RemoteAddress
,
641 SpdSel
->RemoteAddressCount
646 // Check the local and remote addresses for inbound traffic
648 SpdMatch
= (BOOLEAN
) (SpdMatch
||
650 IpSecMatchIpAddress (
653 SpdSel
->LocalAddress
,
654 SpdSel
->LocalAddressCount
656 IpSecMatchIpAddress (
659 SpdSel
->RemoteAddress
,
660 SpdSel
->RemoteAddressCount
665 // Check the next layer protocol and local and remote ports.
667 SpdMatch
= (BOOLEAN
) (SpdMatch
&&
668 IpSecMatchNextLayerProtocol (
671 SpdSel
->NextLayerProtocol
,
680 // Find the right SPD entry if match the 5 key elements.
682 *Action
= SpdEntry
->Data
->Action
;
686 return EFI_NOT_FOUND
;
690 The call back function of NetbufFromExt.
692 @param[in] Arg The argument passed from the caller.
697 IpSecOnRecyclePacket (
704 This is a Notification function. It is called when the related IP6_TXTOKEN_WRAP
707 @param[in] Event The related event.
708 @param[in] Context The data passed by the caller.
713 IpSecRecycleCallback (
718 IPSEC_RECYCLE_CONTEXT
*RecycleContext
;
720 RecycleContext
= (IPSEC_RECYCLE_CONTEXT
*) Context
;
722 if (RecycleContext
->FragmentTable
!= NULL
) {
723 FreePool (RecycleContext
->FragmentTable
);
726 if (RecycleContext
->PayloadBuffer
!= NULL
) {
727 FreePool (RecycleContext
->PayloadBuffer
);
730 FreePool (RecycleContext
);
731 gBS
->CloseEvent (Event
);
736 Calculate the extension hader of IP. The return length only doesn't contain
737 the fixed IP header length.
739 @param[in] IpHead Points to an IP head to be calculated.
740 @param[in] LastHead Points to the last header of the IP header.
742 @return The length of the extension header.
746 IpSecGetPlainExtHeadSize (
753 Size
= (UINT16
) (LastHead
- (UINT8
*) IpHead
);
755 if (Size
> sizeof (EFI_IP6_HEADER
)) {
757 // * (LastHead+1) point the last header's length but not include the first
758 // 8 octers, so this formluation add 8 at the end.
760 Size
= (UINT16
) (Size
- sizeof (EFI_IP6_HEADER
) + *(LastHead
+ 1) + 8);
769 Verify if the Authentication payload is correct.
771 @param[in] EspBuffer Points to the ESP wrapped buffer.
772 @param[in] EspSize The size of the ESP wrapped buffer.
773 @param[in] SadEntry The related SAD entry to store the authentication
775 @param[in] IcvSize The length of ICV.
777 @retval EFI_SUCCESS The authentication data is correct.
778 @retval EFI_ACCESS_DENIED The authentication data is not correct.
782 IpSecEspAuthVerifyPayload (
785 IN IPSEC_SAD_ENTRY
*SadEntry
,
792 HASH_DATA_FRAGMENT HashFragment
[1];
795 // Calculate the size of authentication payload.
797 AuthSize
= EspSize
- IcvSize
;
800 // Calculate the icv buffer and size of the payload.
802 HashFragment
[0].Data
= EspBuffer
;
803 HashFragment
[0].DataSize
= AuthSize
;
805 Status
= IpSecCryptoIoHmac (
806 SadEntry
->Data
->AlgoInfo
.EspAlgoInfo
.AuthAlgoId
,
807 SadEntry
->Data
->AlgoInfo
.EspAlgoInfo
.AuthKey
,
808 SadEntry
->Data
->AlgoInfo
.EspAlgoInfo
.AuthKeyLength
,
814 if (EFI_ERROR (Status
)) {
819 // Compare the calculated icv and the appended original icv.
821 if (CompareMem (EspBuffer
+ AuthSize
, IcvBuffer
, IcvSize
) == 0) {
825 DEBUG ((DEBUG_ERROR
, "Error auth verify payload\n"));
826 return EFI_ACCESS_DENIED
;
830 Search the related SAD entry by the input .
832 @param[in] IpHead The pointer to IP header.
833 @param[in] IpVersion The version of IP (IP4 or IP6).
834 @param[in] Spi The SPI used to search the related SAD entry.
837 @retval NULL Not find the related SAD entry.
838 @retval IPSEC_SAD_ENTRY Return the related SAD entry.
842 IpSecFoundSadFromInboundPacket (
848 EFI_IP_ADDRESS DestIp
;
851 // Parse destination address from ip header.
853 ZeroMem (&DestIp
, sizeof (EFI_IP_ADDRESS
));
854 if (IpVersion
== IP_VERSION_4
) {
857 &((IP4_HEAD
*) IpHead
)->Dst
,
863 &((EFI_IP6_HEADER
*) IpHead
)->DestinationAddress
,
864 sizeof (EFI_IPv6_ADDRESS
)
869 // Lookup SAD entry according to the spi and dest address.
871 return IpSecLookupSadBySpi (Spi
, &DestIp
, IpVersion
);
875 Validate the IP6 extension header format for both the packets we received
876 and that we will transmit.
878 @param[in] NextHeader The next header field in IPv6 basic header.
879 @param[in] ExtHdrs The first bye of the option.
880 @param[in] ExtHdrsLen The length of the whole option.
881 @param[out] LastHeader The pointer of NextHeader of the last extension
882 header processed by IP6.
883 @param[out] RealExtsLen The length of extension headers processed by IP6 layer.
884 This is an optional parameter that may be NULL.
886 @retval TRUE The option is properly formated.
887 @retval FALSE The option is malformated.
891 IpSecIsIp6ExtsValid (
892 IN UINT8
*NextHeader
,
894 IN UINT32 ExtHdrsLen
,
895 OUT UINT8
**LastHeader
,
896 OUT UINT32
*RealExtsLen OPTIONAL
906 if (RealExtsLen
!= NULL
) {
910 *LastHeader
= NextHeader
;
912 if (ExtHdrs
== NULL
&& ExtHdrsLen
== 0) {
916 if ((ExtHdrs
== NULL
&& ExtHdrsLen
!= 0) || (ExtHdrs
!= NULL
&& ExtHdrsLen
== 0)) {
925 while (Pointer
<= ExtHdrsLen
) {
927 switch (*NextHeader
) {
936 case IP6_DESTINATION
:
937 if (*NextHeader
== IP6_DESTINATION
) {
945 NextHeader
= ExtHdrs
+ Pointer
;
948 Option
= ExtHdrs
+ Pointer
;
949 OptionLen
= (UINT8
) ((*Option
+ 1) * 8 - 2);
953 Pointer
= Pointer
+ OptionLen
;
961 // RFC2402, AH header should after fragment header.
967 NextHeader
= ExtHdrs
+ Pointer
;
968 Pointer
= Pointer
+ 8;
976 Option
= ExtHdrs
+ Pointer
;
980 // RFC2402, Payload length is specified in 32-bit words, minus "2".
982 OptionLen
= (UINT8
) ((*Option
+ 2) * 4);
983 Pointer
= Pointer
+ OptionLen
;
987 *LastHeader
= NextHeader
;
988 if (RealExtsLen
!= NULL
) {
989 *RealExtsLen
= Pointer
;
996 *LastHeader
= NextHeader
;
998 if (RealExtsLen
!= NULL
) {
999 *RealExtsLen
= Pointer
;
1006 The actual entry to process the tunnel header and inner header for tunnel mode
1009 This function is the subfunction of IpSecEspInboundPacket(). It change the destination
1010 Ip address to the station address and recalculate the uplayyer's checksum.
1013 @param[in, out] IpHead Points to the IP header containing the ESP header
1014 to be trimed on input, and without ESP header
1016 @param[in] IpPayload The decrypted Ip payload. It start from the inner
1018 @param[in] IpVersion The version of IP.
1019 @param[in] SadData Pointer of the relevant SAD.
1020 @param[in, out] LastHead The Last Header in IP header on return.
1024 IpSecTunnelInboundPacket (
1025 IN OUT UINT8
*IpHead
,
1026 IN UINT8
*IpPayload
,
1028 IN IPSEC_SAD_DATA
*SadData
,
1029 IN OUT UINT8
*LastHead
1032 EFI_UDP_HEADER
*UdpHeader
;
1033 TCP_HEAD
*TcpHeader
;
1035 UINT16 PseudoChecksum
;
1036 UINT16 PacketChecksum
;
1038 IP6_ICMP_HEAD
*Icmp6Head
;
1042 if (IpVersion
== IP_VERSION_4
) {
1044 // Zero OutIP header use this to indicate the input packet is under
1045 // IPsec Tunnel protected.
1052 &((IP4_HEAD
*)IpPayload
)->Dst
,
1053 &SadData
->TunnelDestAddress
.v4
,
1054 sizeof (EFI_IPv4_ADDRESS
)
1058 // Recalculate IpHeader Checksum
1060 if (((IP4_HEAD
*)(IpPayload
))->Checksum
!= 0 ) {
1061 ((IP4_HEAD
*)(IpPayload
))->Checksum
= 0;
1062 ((IP4_HEAD
*)(IpPayload
))->Checksum
= (UINT16
) (~NetblockChecksum (
1064 ((IP4_HEAD
*)IpPayload
)->HeadLen
<< 2
1071 // Recalcualte PseudoChecksum
1073 switch (((IP4_HEAD
*)IpPayload
)->Protocol
) {
1074 case EFI_IP_PROTO_UDP
:
1075 UdpHeader
= (EFI_UDP_HEADER
*)((UINT8
*)IpPayload
+ (((IP4_HEAD
*)IpPayload
)->HeadLen
<< 2));
1076 Checksum
= & UdpHeader
->Checksum
;
1080 case EFI_IP_PROTO_TCP
:
1081 TcpHeader
= (TCP_HEAD
*) ((UINT8
*)IpPayload
+ (((IP4_HEAD
*)IpPayload
)->HeadLen
<< 2));
1082 Checksum
= &TcpHeader
->Checksum
;
1089 PacketChecksum
= NetblockChecksum (
1090 (UINT8
*)IpPayload
+ (((IP4_HEAD
*)IpPayload
)->HeadLen
<< 2),
1091 NTOHS (((IP4_HEAD
*)IpPayload
)->TotalLen
) - (((IP4_HEAD
*)IpPayload
)->HeadLen
<< 2)
1093 PseudoChecksum
= NetPseudoHeadChecksum (
1094 ((IP4_HEAD
*)IpPayload
)->Src
,
1095 ((IP4_HEAD
*)IpPayload
)->Dst
,
1096 ((IP4_HEAD
*)IpPayload
)->Protocol
,
1100 if (Checksum
!= NULL
) {
1101 *Checksum
= NetAddChecksum (PacketChecksum
, PseudoChecksum
);
1102 *Checksum
= (UINT16
) ~(NetAddChecksum (*Checksum
, HTONS((UINT16
)(NTOHS (((IP4_HEAD
*)IpPayload
)->TotalLen
) - (((IP4_HEAD
*)IpPayload
)->HeadLen
<< 2)))));
1106 // Zero OutIP header use this to indicate the input packet is under
1107 // IPsec Tunnel protected.
1111 sizeof (EFI_IP6_HEADER
)
1114 &((EFI_IP6_HEADER
*)IpPayload
)->DestinationAddress
,
1115 &SadData
->TunnelDestAddress
.v6
,
1116 sizeof (EFI_IPv6_ADDRESS
)
1120 // Get the Extension Header and Header length.
1122 IpSecIsIp6ExtsValid (
1123 &((EFI_IP6_HEADER
*)IpPayload
)->NextHeader
,
1124 IpPayload
+ sizeof (EFI_IP6_HEADER
),
1125 ((EFI_IP6_HEADER
*)IpPayload
)->PayloadLength
,
1131 // Recalcualte PseudoChecksum
1133 switch (*LastHead
) {
1134 case EFI_IP_PROTO_UDP
:
1135 UdpHeader
= (EFI_UDP_HEADER
*)((UINT8
*)IpPayload
+ sizeof (EFI_IP6_HEADER
) + OptionLen
);
1136 Checksum
= &UdpHeader
->Checksum
;
1140 case EFI_IP_PROTO_TCP
:
1141 TcpHeader
= (TCP_HEAD
*)(IpPayload
+ sizeof (EFI_IP6_HEADER
) + OptionLen
);
1142 Checksum
= &TcpHeader
->Checksum
;
1147 Icmp6Head
= (IP6_ICMP_HEAD
*) (IpPayload
+ sizeof (EFI_IP6_HEADER
) + OptionLen
);
1148 Checksum
= &Icmp6Head
->Checksum
;
1152 PacketChecksum
= NetblockChecksum (
1153 IpPayload
+ sizeof (EFI_IP6_HEADER
) + OptionLen
,
1154 NTOHS(((EFI_IP6_HEADER
*)IpPayload
)->PayloadLength
) - OptionLen
1156 PseudoChecksum
= NetIp6PseudoHeadChecksum (
1157 &((EFI_IP6_HEADER
*)IpPayload
)->SourceAddress
,
1158 &((EFI_IP6_HEADER
*)IpPayload
)->DestinationAddress
,
1163 if (Checksum
!= NULL
) {
1164 *Checksum
= NetAddChecksum (PacketChecksum
, PseudoChecksum
);
1165 *Checksum
= (UINT16
) ~(NetAddChecksum (
1167 HTONS ((UINT16
)((NTOHS (((EFI_IP6_HEADER
*)(IpPayload
))->PayloadLength
)) - OptionLen
))
1174 The actual entry to create inner header for tunnel mode inbound traffic.
1176 This function is the subfunction of IpSecEspOutboundPacket(). It create
1177 the sending packet by encrypting its payload and inserting ESP header in the orginal
1178 IP header, then return the IpHeader and IPsec protected Fragmentable.
1180 @param[in, out] IpHead Points to IP header containing the orginal IP header
1181 to be processed on input, and inserted ESP header
1183 @param[in] IpVersion The version of IP.
1184 @param[in] SadData The related SAD data.
1185 @param[in, out] LastHead The Last Header in IP header.
1186 @param[in] OptionsBuffer Pointer to the options buffer.
1187 @param[in] OptionsLength Length of the options buffer.
1188 @param[in, out] FragmentTable Pointer to a list of fragments to be protected by
1189 IPsec on input, and with IPsec protected
1191 @param[in] FragmentCount The number of fragments.
1195 IpSecTunnelOutboundPacket (
1196 IN OUT UINT8
*IpHead
,
1198 IN IPSEC_SAD_DATA
*SadData
,
1199 IN OUT UINT8
*LastHead
,
1200 IN VOID
**OptionsBuffer
,
1201 IN UINT32
*OptionsLength
,
1202 IN OUT EFI_IPSEC_FRAGMENT_DATA
**FragmentTable
,
1203 IN UINT32
*FragmentCount
1208 UINT16 PacketChecksum
;
1210 UINT16 PseudoChecksum
;
1211 IP6_ICMP_HEAD
*IcmpHead
;
1214 if (OptionsLength
== NULL
) {
1218 if (IpVersion
== IP_VERSION_4
) {
1219 InnerHead
= AllocateZeroPool (sizeof (IP4_HEAD
) + *OptionsLength
);
1220 if (InnerHead
== NULL
) {
1230 InnerHead
+ sizeof (IP4_HEAD
),
1235 InnerHead
= AllocateZeroPool (sizeof (EFI_IP6_HEADER
) + *OptionsLength
);
1236 if (InnerHead
== NULL
) {
1243 sizeof (EFI_IP6_HEADER
)
1246 InnerHead
+ sizeof (EFI_IP6_HEADER
),
1251 if (OptionsBuffer
!= NULL
) {
1252 if (*OptionsLength
!= 0) {
1254 *OptionsBuffer
= NULL
;
1260 // 2. Reassamlbe Fragment into Packet
1262 Packet
= NetbufFromExt (
1263 (NET_FRAGMENT
*)(*FragmentTable
),
1267 IpSecOnRecyclePacket
,
1270 if (Packet
== NULL
) {
1271 FreePool (InnerHead
);
1276 // 3. Check the Last Header, if it is TCP, UDP or ICMP recalcualate its pesudo
1279 switch (*LastHead
) {
1280 case EFI_IP_PROTO_UDP
:
1281 Packet
->Udp
= (EFI_UDP_HEADER
*) NetbufGetByte (Packet
, 0, 0);
1282 ASSERT (Packet
->Udp
!= NULL
);
1283 Checksum
= &Packet
->Udp
->Checksum
;
1287 case EFI_IP_PROTO_TCP
:
1288 Packet
->Tcp
= (TCP_HEAD
*) NetbufGetByte (Packet
, 0, 0);
1289 ASSERT (Packet
->Tcp
!= NULL
);
1290 Checksum
= &Packet
->Tcp
->Checksum
;
1295 IcmpHead
= (IP6_ICMP_HEAD
*) NetbufGetByte (Packet
, 0, NULL
);
1296 ASSERT (IcmpHead
!= NULL
);
1297 Checksum
= &IcmpHead
->Checksum
;
1305 PacketChecksum
= NetbufChecksum (Packet
);
1307 if (IpVersion
== IP_VERSION_4
) {
1309 // Replace the source address of Inner Header.
1312 &((IP4_HEAD
*)InnerHead
)->Src
,
1313 &SadData
->SpdSelector
->LocalAddress
[0].Address
.v4
,
1314 sizeof (EFI_IPv4_ADDRESS
)
1317 PacketChecksum
= NetbufChecksum (Packet
);
1318 PseudoChecksum
= NetPseudoHeadChecksum (
1319 ((IP4_HEAD
*)InnerHead
)->Src
,
1320 ((IP4_HEAD
*)InnerHead
)->Dst
,
1327 // Replace the source address of Inner Header.
1330 &((EFI_IP6_HEADER
*)InnerHead
)->SourceAddress
,
1331 &(SadData
->SpdSelector
->LocalAddress
[0].Address
.v6
),
1332 sizeof (EFI_IPv6_ADDRESS
)
1334 PacketChecksum
= NetbufChecksum (Packet
);
1335 PseudoChecksum
= NetIp6PseudoHeadChecksum (
1336 &((EFI_IP6_HEADER
*)InnerHead
)->SourceAddress
,
1337 &((EFI_IP6_HEADER
*)InnerHead
)->DestinationAddress
,
1343 if (Checksum
!= NULL
) {
1344 *Checksum
= NetAddChecksum (PacketChecksum
, PseudoChecksum
);
1345 *Checksum
= (UINT16
) ~(NetAddChecksum ((UINT16
)*Checksum
, HTONS ((UINT16
) Packet
->TotalSize
)));
1348 if (Packet
!= NULL
) {
1349 NetbufFree (Packet
);
1355 The actual entry to relative function processes the inbound traffic of ESP header.
1357 This function is the subfunction of IpSecProtectInboundPacket(). It checks the
1358 received packet security property and trim the ESP header and then returns without
1359 an IPsec protected IP Header and FramgmentTable.
1361 @param[in] IpVersion The version of IP.
1362 @param[in, out] IpHead Points to the IP header containing the ESP header
1363 to be trimed on input, and without ESP header
1365 @param[out] LastHead The Last Header in IP header on return.
1366 @param[in, out] OptionsBuffer Pointer to the options buffer.
1367 @param[in, out] OptionsLength Length of the options buffer.
1368 @param[in, out] FragmentTable Pointer to a list of fragments in the form of IPsec
1369 protected on input, and without IPsec protected
1371 @param[in, out] FragmentCount The number of fragments.
1372 @param[out] SpdSelector Pointer to contain the address of SPD selector on return.
1373 @param[out] RecycleEvent The event for recycling of resources.
1375 @retval EFI_SUCCESS The operation was successful.
1376 @retval EFI_ACCESS_DENIED One or more following conditions is TRUE:
1377 - ESP header was not found or mal-format.
1378 - The related SAD entry was not found.
1379 - The related SAD entry does not support the ESP protocol.
1380 @retval EFI_OUT_OF_RESOURCES The required system resource can't be allocated.
1384 IpSecEspInboundPacket (
1386 IN OUT VOID
*IpHead
,
1387 OUT UINT8
*LastHead
,
1388 IN OUT VOID
**OptionsBuffer
,
1389 IN OUT UINT32
*OptionsLength
,
1390 IN OUT EFI_IPSEC_FRAGMENT_DATA
**FragmentTable
,
1391 IN OUT UINT32
*FragmentCount
,
1392 OUT EFI_IPSEC_SPD_SELECTOR
**SpdSelector
,
1393 OUT EFI_EVENT
*RecycleEvent
1402 UINTN PlainPayloadSize
;
1405 UINT8
*ProcessBuffer
;
1406 EFI_ESP_HEADER
*EspHeader
;
1407 EFI_ESP_TAIL
*EspTail
;
1408 EFI_IPSEC_SA_ID
*SaId
;
1409 IPSEC_SAD_DATA
*SadData
;
1410 IPSEC_SAD_ENTRY
*SadEntry
;
1411 IPSEC_RECYCLE_CONTEXT
*RecycleContext
;
1413 UINT16 IpSecHeadSize
;
1416 Status
= EFI_SUCCESS
;
1418 ProcessBuffer
= NULL
;
1419 RecycleContext
= NULL
;
1420 *RecycleEvent
= NULL
;
1421 PlainPayloadSize
= 0;
1425 // Build netbuf from fragment table first.
1427 Payload
= NetbufFromExt (
1428 (NET_FRAGMENT
*) *FragmentTable
,
1431 sizeof (EFI_ESP_HEADER
),
1432 IpSecOnRecyclePacket
,
1435 if (Payload
== NULL
) {
1436 Status
= EFI_OUT_OF_RESOURCES
;
1441 // Get the esp size and esp header from netbuf.
1443 EspSize
= Payload
->TotalSize
;
1444 EspHeader
= (EFI_ESP_HEADER
*) NetbufGetByte (Payload
, 0, NULL
);
1446 if (EspHeader
== NULL
) {
1447 Status
= EFI_ACCESS_DENIED
;
1452 // Parse destination address from ip header and found the related SAD Entry.
1454 SadEntry
= IpSecFoundSadFromInboundPacket (
1457 NTOHL (EspHeader
->Spi
)
1460 if (SadEntry
== NULL
) {
1461 Status
= EFI_ACCESS_DENIED
;
1465 SaId
= SadEntry
->Id
;
1466 SadData
= SadEntry
->Data
;
1469 // Only support esp protocol currently.
1471 if (SaId
->Proto
!= EfiIPsecESP
) {
1472 Status
= EFI_ACCESS_DENIED
;
1476 if (!SadData
->ManualSet
) {
1478 // TODO: Check SA lifetime and sequence number
1483 // Allocate buffer for decryption and authentication.
1485 ProcessBuffer
= AllocateZeroPool (EspSize
);
1486 if (ProcessBuffer
== NULL
) {
1487 Status
= EFI_OUT_OF_RESOURCES
;
1491 NetbufCopy (Payload
, 0, (UINT32
) EspSize
, ProcessBuffer
);
1494 // Get the IcvSize for authentication and BlockSize/IvSize for Decryption.
1496 IcvSize
= IpSecGetIcvLength (SadEntry
->Data
->AlgoInfo
.EspAlgoInfo
.AuthAlgoId
);
1497 IvSize
= IpSecGetEncryptIvLength (SadEntry
->Data
->AlgoInfo
.EspAlgoInfo
.EncAlgoId
);
1498 BlockSize
= IpSecGetEncryptBlockSize (SadEntry
->Data
->AlgoInfo
.EspAlgoInfo
.EncAlgoId
);
1501 // Make sure the ESP packet is not mal-formt.
1502 // 1. Check whether the Espsize is larger than ESP header + IvSize + EspTail + IcvSize.
1503 // 2. Check whether the left payload size is multiple of IvSize.
1505 MiscSize
= sizeof (EFI_ESP_HEADER
) + IvSize
+ IcvSize
;
1506 if (EspSize
<= (MiscSize
+ sizeof (EFI_ESP_TAIL
))) {
1507 Status
= EFI_ACCESS_DENIED
;
1510 if ((EspSize
- MiscSize
) % BlockSize
!= 0) {
1511 Status
= EFI_ACCESS_DENIED
;
1516 // Authenticate the ESP packet.
1518 if (SadData
->AlgoInfo
.EspAlgoInfo
.AuthKey
!= NULL
) {
1519 Status
= IpSecEspAuthVerifyPayload (
1525 if (EFI_ERROR (Status
)) {
1530 // Decrypt the payload by the SAD entry if it has decrypt key.
1532 if (SadData
->AlgoInfo
.EspAlgoInfo
.EncKey
!= NULL
) {
1533 Status
= IpSecCryptoIoDecrypt (
1534 SadEntry
->Data
->AlgoInfo
.EspAlgoInfo
.EncAlgoId
,
1535 SadEntry
->Data
->AlgoInfo
.EspAlgoInfo
.EncKey
,
1536 SadEntry
->Data
->AlgoInfo
.EspAlgoInfo
.EncKeyLength
<< 3,
1537 ProcessBuffer
+ sizeof (EFI_ESP_HEADER
),
1538 ProcessBuffer
+ sizeof (EFI_ESP_HEADER
) + IvSize
,
1539 EspSize
- sizeof (EFI_ESP_HEADER
) - IvSize
- IcvSize
,
1540 ProcessBuffer
+ sizeof (EFI_ESP_HEADER
) + IvSize
1542 if (EFI_ERROR (Status
)) {
1548 // Parse EspTail and compute the plain payload size.
1550 EspTail
= (EFI_ESP_TAIL
*) (ProcessBuffer
+ EspSize
- IcvSize
- sizeof (EFI_ESP_TAIL
));
1551 PaddingSize
= EspTail
->PaddingLength
;
1552 NextHeader
= EspTail
->NextHeader
;
1554 if (EspSize
<= (MiscSize
+ sizeof (EFI_ESP_TAIL
) + PaddingSize
)) {
1555 Status
= EFI_ACCESS_DENIED
;
1558 PlainPayloadSize
= EspSize
- MiscSize
- sizeof (EFI_ESP_TAIL
) - PaddingSize
;
1561 // TODO: handle anti-replay window
1564 // Decryption and authentication with esp has been done, so it's time to
1565 // reload the new packet, create recycle event and fixup ip header.
1567 RecycleContext
= AllocateZeroPool (sizeof (IPSEC_RECYCLE_CONTEXT
));
1568 if (RecycleContext
== NULL
) {
1569 Status
= EFI_OUT_OF_RESOURCES
;
1573 Status
= gBS
->CreateEvent (
1576 IpSecRecycleCallback
,
1580 if (EFI_ERROR (Status
)) {
1585 // The caller will take responsible to handle the original fragment table
1587 *FragmentTable
= AllocateZeroPool (sizeof (EFI_IPSEC_FRAGMENT_DATA
));
1588 if (*FragmentTable
== NULL
) {
1589 Status
= EFI_OUT_OF_RESOURCES
;
1593 RecycleContext
->PayloadBuffer
= ProcessBuffer
;
1594 RecycleContext
->FragmentTable
= *FragmentTable
;
1597 // If Tunnel, recalculate upper-layyer PesudoCheckSum and trim the out
1599 if (SadData
->Mode
== EfiIPsecTunnel
) {
1600 InnerHead
= ProcessBuffer
+ sizeof (EFI_ESP_HEADER
) + IvSize
;
1601 IpSecTunnelInboundPacket (
1609 if (IpVersion
== IP_VERSION_4
) {
1610 (*FragmentTable
)[0].FragmentBuffer
= InnerHead
;
1611 (*FragmentTable
)[0].FragmentLength
= (UINT32
) PlainPayloadSize
;
1614 (*FragmentTable
)[0].FragmentBuffer
= InnerHead
;
1615 (*FragmentTable
)[0].FragmentLength
= (UINT32
) PlainPayloadSize
;
1618 (*FragmentTable
)[0].FragmentBuffer
= ProcessBuffer
+ sizeof (EFI_ESP_HEADER
) + IvSize
;
1619 (*FragmentTable
)[0].FragmentLength
= (UINT32
) PlainPayloadSize
;
1625 // Update the total length field in ip header since processed by esp.
1627 if (SadData
->Mode
!= EfiIPsecTunnel
) {
1628 if (IpVersion
== IP_VERSION_4
) {
1629 ((IP4_HEAD
*) IpHead
)->TotalLen
= HTONS ((UINT16
) ((((IP4_HEAD
*) IpHead
)->HeadLen
<< 2) + PlainPayloadSize
));
1631 IpSecHeadSize
= IpSecGetPlainExtHeadSize (IpHead
, LastHead
);
1632 ((EFI_IP6_HEADER
*) IpHead
)->PayloadLength
= HTONS ((UINT16
)(IpSecHeadSize
+ PlainPayloadSize
));
1635 // Update the next layer field in ip header since esp header inserted.
1637 *LastHead
= NextHeader
;
1642 // Update the SPD association of the SAD entry.
1644 *SpdSelector
= SadData
->SpdSelector
;
1647 if (Payload
!= NULL
) {
1648 NetbufFree (Payload
);
1651 if (EFI_ERROR (Status
)) {
1652 if (ProcessBuffer
!= NULL
) {
1653 FreePool (ProcessBuffer
);
1656 if (RecycleContext
!= NULL
) {
1657 FreePool (RecycleContext
);
1660 if (*RecycleEvent
!= NULL
) {
1661 gBS
->CloseEvent (*RecycleEvent
);
1669 The actual entry to the relative function processes the output traffic using the ESP protocol.
1671 This function is the subfunction of IpSecProtectOutboundPacket(). It protected
1672 the sending packet by encrypting its payload and inserting ESP header in the orginal
1673 IP header, then return the IpHeader and IPsec protected Fragmentable.
1675 @param[in] IpVersion The version of IP.
1676 @param[in, out] IpHead Points to IP header containing the orginal IP header
1677 to be processed on input, and inserted ESP header
1679 @param[in, out] LastHead The Last Header in IP header.
1680 @param[in, out] OptionsBuffer Pointer to the options buffer.
1681 @param[in, out] OptionsLength Length of the options buffer.
1682 @param[in, out] FragmentTable Pointer to a list of fragments to be protected by
1683 IPsec on input, and with IPsec protected
1685 @param[in, out] FragmentCount The number of fragments.
1686 @param[in] SadEntry The related SAD entry.
1687 @param[out] RecycleEvent The event for recycling of resources.
1689 @retval EFI_SUCCESS The operation was successful.
1690 @retval EFI_OUT_OF_RESOURCES The required system resources can't be allocated.
1694 IpSecEspOutboundPacket (
1696 IN OUT VOID
*IpHead
,
1697 IN OUT UINT8
*LastHead
,
1698 IN OUT VOID
**OptionsBuffer
,
1699 IN OUT UINT32
*OptionsLength
,
1700 IN OUT EFI_IPSEC_FRAGMENT_DATA
**FragmentTable
,
1701 IN OUT UINT32
*FragmentCount
,
1702 IN IPSEC_SAD_ENTRY
*SadEntry
,
1703 OUT EFI_EVENT
*RecycleEvent
1708 EFI_IPSEC_SA_ID
*SaId
;
1709 IPSEC_SAD_DATA
*SadData
;
1710 IPSEC_RECYCLE_CONTEXT
*RecycleContext
;
1711 UINT8
*ProcessBuffer
;
1713 INTN EncryptBlockSize
;// Size of encryption block, 4 bytes aligned and >= 4
1714 UINTN EspSize
; // Total size of esp wrapped ip payload
1715 UINTN IvSize
; // Size of IV, optional, might be 0
1716 UINTN PlainPayloadSize
;// Original IP payload size
1717 UINTN PaddingSize
; // Size of padding
1718 UINTN EncryptSize
; // Size of data to be encrypted, start after IV and
1720 UINTN IcvSize
; // Size of ICV, optional, might be 0
1721 UINT8
*RestOfPayload
; // Start of Payload after IV
1722 UINT8
*Padding
; // Start address of padding
1723 EFI_ESP_HEADER
*EspHeader
; // Start address of ESP frame
1724 EFI_ESP_TAIL
*EspTail
; // Address behind padding
1726 HASH_DATA_FRAGMENT HashFragment
[1];
1728 Status
= EFI_ACCESS_DENIED
;
1729 SaId
= SadEntry
->Id
;
1730 SadData
= SadEntry
->Data
;
1731 ProcessBuffer
= NULL
;
1732 RecycleContext
= NULL
;
1733 *RecycleEvent
= NULL
;
1736 if (!SadData
->ManualSet
&&
1737 SadData
->AlgoInfo
.EspAlgoInfo
.EncKey
== NULL
&&
1738 SadData
->AlgoInfo
.EspAlgoInfo
.AuthKey
== NULL
1741 // Invalid manual SAD entry configuration.
1747 // Create OutHeader according to Inner Header
1749 if (SadData
->Mode
== EfiIPsecTunnel
) {
1750 InnerHead
= IpSecTunnelOutboundPacket (
1761 if (InnerHead
== NULL
) {
1762 return EFI_INVALID_PARAMETER
;
1768 // Calculate enctrypt block size, need iv by default and 4 bytes alignment.
1770 EncryptBlockSize
= 4;
1772 if (SadData
->AlgoInfo
.EspAlgoInfo
.EncKey
!= NULL
) {
1773 EncryptBlockSize
= IpSecGetEncryptBlockSize (SadEntry
->Data
->AlgoInfo
.EspAlgoInfo
.EncAlgoId
);
1775 if (EncryptBlockSize
< 0 || (EncryptBlockSize
!= 1 && EncryptBlockSize
% 4 != 0)) {
1781 // Calculate the plain payload size according to the fragment table.
1783 PlainPayloadSize
= 0;
1784 for (Index
= 0; Index
< *FragmentCount
; Index
++) {
1785 PlainPayloadSize
+= (*FragmentTable
)[Index
].FragmentLength
;
1789 // Add IPHeader size for Tunnel Mode
1791 if (SadData
->Mode
== EfiIPsecTunnel
) {
1792 if (IpVersion
== IP_VERSION_4
) {
1793 PlainPayloadSize
+= sizeof (IP4_HEAD
);
1795 PlainPayloadSize
+= sizeof (EFI_IP6_HEADER
);
1798 // OPtions should be encryption into it
1800 PlainPayloadSize
+= *OptionsLength
;
1805 // Calculate icv size, optional by default and 4 bytes alignment.
1808 if (SadData
->AlgoInfo
.EspAlgoInfo
.AuthKey
!= NULL
) {
1809 IcvSize
= IpSecGetIcvLength (SadEntry
->Data
->AlgoInfo
.EspAlgoInfo
.AuthAlgoId
);
1810 if (IcvSize
% 4 != 0) {
1816 // Calcuate the total size of esp wrapped ip payload.
1818 IvSize
= IpSecGetEncryptIvLength (SadEntry
->Data
->AlgoInfo
.EspAlgoInfo
.EncAlgoId
);
1819 EncryptSize
= (PlainPayloadSize
+ sizeof (EFI_ESP_TAIL
) + EncryptBlockSize
- 1) / EncryptBlockSize
* EncryptBlockSize
;
1820 PaddingSize
= EncryptSize
- PlainPayloadSize
- sizeof (EFI_ESP_TAIL
);
1821 EspSize
= sizeof (EFI_ESP_HEADER
) + IvSize
+ EncryptSize
+ IcvSize
;
1823 ProcessBuffer
= AllocateZeroPool (EspSize
);
1824 if (ProcessBuffer
== NULL
) {
1825 Status
= EFI_OUT_OF_RESOURCES
;
1830 // Calculate esp header and esp tail including header, payload and padding.
1832 EspHeader
= (EFI_ESP_HEADER
*) ProcessBuffer
;
1833 RestOfPayload
= (UINT8
*) (EspHeader
+ 1) + IvSize
;
1834 Padding
= RestOfPayload
+ PlainPayloadSize
;
1835 EspTail
= (EFI_ESP_TAIL
*) (Padding
+ PaddingSize
);
1838 // Fill the sn and spi fields in esp header.
1840 EspHeader
->SequenceNumber
= HTONL ((UINT32
) SadData
->SequenceNumber
+ 1);
1841 //EspHeader->SequenceNumber = HTONL ((UINT32) SadData->SequenceNumber);
1842 EspHeader
->Spi
= HTONL (SaId
->Spi
);
1845 // Copy the rest of payload (after iv) from the original fragment buffer.
1852 if (SadData
->Mode
== EfiIPsecTunnel
) {
1853 if (IpVersion
== IP_VERSION_4
) {
1855 // HeadLen, Total Length
1857 ((IP4_HEAD
*)InnerHead
)->HeadLen
= (UINT8
) ((sizeof (IP4_HEAD
) + *OptionsLength
) >> 2);
1858 ((IP4_HEAD
*)InnerHead
)->TotalLen
= HTONS ((UINT16
) PlainPayloadSize
);
1859 ((IP4_HEAD
*)InnerHead
)->Checksum
= 0;
1860 ((IP4_HEAD
*)InnerHead
)->Checksum
= (UINT16
) (~NetblockChecksum (
1865 RestOfPayload
+ BytesCopied
,
1867 sizeof (IP4_HEAD
) + *OptionsLength
1869 BytesCopied
+= sizeof (IP4_HEAD
) + *OptionsLength
;
1872 ((EFI_IP6_HEADER
*)InnerHead
)->PayloadLength
= HTONS ((UINT16
) (PlainPayloadSize
- sizeof (EFI_IP6_HEADER
)));
1874 RestOfPayload
+ BytesCopied
,
1876 sizeof (EFI_IP6_HEADER
) + *OptionsLength
1878 BytesCopied
+= sizeof (EFI_IP6_HEADER
) + *OptionsLength
;
1882 for (Index
= 0; Index
< *FragmentCount
; Index
++) {
1884 (RestOfPayload
+ BytesCopied
),
1885 (*FragmentTable
)[Index
].FragmentBuffer
,
1886 (*FragmentTable
)[Index
].FragmentLength
1888 BytesCopied
+= (*FragmentTable
)[Index
].FragmentLength
;
1891 // Fill the padding buffer by natural number sequence.
1893 for (Index
= 0; Index
< PaddingSize
; Index
++) {
1894 Padding
[Index
] = (UINT8
) (Index
+ 1);
1897 // Fill the padding length and next header fields in esp tail.
1899 EspTail
->PaddingLength
= (UINT8
) PaddingSize
;
1900 EspTail
->NextHeader
= *LastHead
;
1903 // Fill the next header for Tunnel mode.
1905 if (SadData
->Mode
== EfiIPsecTunnel
) {
1906 if (IpVersion
== IP_VERSION_4
) {
1907 EspTail
->NextHeader
= 4;
1909 EspTail
->NextHeader
= 41;
1914 // Generate iv at random by crypt library.
1916 Status
= IpSecGenerateIv (
1917 (UINT8
*) (EspHeader
+ 1),
1922 if (EFI_ERROR (Status
)) {
1927 // Encryption the payload (after iv) by the SAD entry if has encrypt key.
1929 if (SadData
->AlgoInfo
.EspAlgoInfo
.EncKey
!= NULL
) {
1930 Status
= IpSecCryptoIoEncrypt (
1931 SadEntry
->Data
->AlgoInfo
.EspAlgoInfo
.EncAlgoId
,
1932 SadEntry
->Data
->AlgoInfo
.EspAlgoInfo
.EncKey
,
1933 SadEntry
->Data
->AlgoInfo
.EspAlgoInfo
.EncKeyLength
<< 3,
1934 (UINT8
*)(EspHeader
+ 1),
1940 if (EFI_ERROR (Status
)) {
1946 // Authenticate the esp wrapped buffer by the SAD entry if it has auth key.
1948 if (SadData
->AlgoInfo
.EspAlgoInfo
.AuthKey
!= NULL
) {
1950 HashFragment
[0].Data
= ProcessBuffer
;
1951 HashFragment
[0].DataSize
= EspSize
- IcvSize
;
1952 Status
= IpSecCryptoIoHmac (
1953 SadEntry
->Data
->AlgoInfo
.EspAlgoInfo
.AuthAlgoId
,
1954 SadEntry
->Data
->AlgoInfo
.EspAlgoInfo
.AuthKey
,
1955 SadEntry
->Data
->AlgoInfo
.EspAlgoInfo
.AuthKeyLength
,
1958 ProcessBuffer
+ EspSize
- IcvSize
,
1961 if (EFI_ERROR (Status
)) {
1967 // Encryption and authentication with esp has been done, so it's time to
1968 // reload the new packet, create recycle event and fixup ip header.
1970 RecycleContext
= AllocateZeroPool (sizeof (IPSEC_RECYCLE_CONTEXT
));
1971 if (RecycleContext
== NULL
) {
1972 Status
= EFI_OUT_OF_RESOURCES
;
1976 Status
= gBS
->CreateEvent (
1979 IpSecRecycleCallback
,
1983 if (EFI_ERROR (Status
)) {
1987 // Caller take responsible to handle the original fragment table.
1989 *FragmentTable
= AllocateZeroPool (sizeof (EFI_IPSEC_FRAGMENT_DATA
));
1990 if (*FragmentTable
== NULL
) {
1991 Status
= EFI_OUT_OF_RESOURCES
;
1995 RecycleContext
->FragmentTable
= *FragmentTable
;
1996 RecycleContext
->PayloadBuffer
= ProcessBuffer
;
1997 (*FragmentTable
)[0].FragmentBuffer
= ProcessBuffer
;
1998 (*FragmentTable
)[0].FragmentLength
= (UINT32
) EspSize
;
2002 // Update the total length field in ip header since processed by esp.
2004 if (IpVersion
== IP_VERSION_4
) {
2005 ((IP4_HEAD
*) IpHead
)->TotalLen
= HTONS ((UINT16
) ((((IP4_HEAD
*) IpHead
)->HeadLen
<< 2) + EspSize
));
2007 ((EFI_IP6_HEADER
*) IpHead
)->PayloadLength
= (UINT16
) (IpSecGetPlainExtHeadSize (IpHead
, LastHead
) + EspSize
);
2011 // If tunnel mode, it should change the outer Ip header with tunnel source address
2012 // and destination tunnel address.
2014 if (SadData
->Mode
== EfiIPsecTunnel
) {
2015 if (IpVersion
== IP_VERSION_4
) {
2017 &((IP4_HEAD
*) IpHead
)->Src
,
2018 &SadData
->TunnelSourceAddress
.v4
,
2019 sizeof (EFI_IPv4_ADDRESS
)
2022 &((IP4_HEAD
*) IpHead
)->Dst
,
2023 &SadData
->TunnelDestAddress
.v4
,
2024 sizeof (EFI_IPv4_ADDRESS
)
2028 &((EFI_IP6_HEADER
*) IpHead
)->SourceAddress
,
2029 &SadData
->TunnelSourceAddress
.v6
,
2030 sizeof (EFI_IPv6_ADDRESS
)
2033 &((EFI_IP6_HEADER
*) IpHead
)->DestinationAddress
,
2034 &SadData
->TunnelDestAddress
.v6
,
2035 sizeof (EFI_IPv6_ADDRESS
)
2041 // Update the next layer field in ip header since esp header inserted.
2043 *LastHead
= IPSEC_ESP_PROTOCOL
;
2046 // Increase the sn number in SAD entry according to rfc4303.
2048 SadData
->SequenceNumber
++;
2051 if (EFI_ERROR (Status
)) {
2052 if (ProcessBuffer
!= NULL
) {
2053 FreePool (ProcessBuffer
);
2056 if (RecycleContext
!= NULL
) {
2057 FreePool (RecycleContext
);
2060 if (*RecycleEvent
!= NULL
) {
2061 gBS
->CloseEvent (*RecycleEvent
);
2069 This function processes the inbound traffic with IPsec.
2071 It checks the received packet security property, trims the ESP/AH header, and then
2072 returns without an IPsec protected IP Header and FragmentTable.
2074 @param[in] IpVersion The version of IP.
2075 @param[in, out] IpHead Points to IP header containing the ESP/AH header
2076 to be trimed on input, and without ESP/AH header
2078 @param[in, out] LastHead The Last Header in IP header on return.
2079 @param[in, out] OptionsBuffer Pointer to the options buffer.
2080 @param[in, out] OptionsLength Length of the options buffer.
2081 @param[in, out] FragmentTable Pointer to a list of fragments in form of IPsec
2082 protected on input, and without IPsec protected
2084 @param[in, out] FragmentCount The number of fragments.
2085 @param[out] SpdEntry Pointer to contain the address of SPD entry on return.
2086 @param[out] RecycleEvent The event for recycling of resources.
2088 @retval EFI_SUCCESS The operation was successful.
2089 @retval EFI_UNSUPPORTED The IPSEC protocol is not supported.
2093 IpSecProtectInboundPacket (
2095 IN OUT VOID
*IpHead
,
2096 IN OUT UINT8
*LastHead
,
2097 IN OUT VOID
**OptionsBuffer
,
2098 IN OUT UINT32
*OptionsLength
,
2099 IN OUT EFI_IPSEC_FRAGMENT_DATA
**FragmentTable
,
2100 IN OUT UINT32
*FragmentCount
,
2101 OUT EFI_IPSEC_SPD_SELECTOR
**SpdEntry
,
2102 OUT EFI_EVENT
*RecycleEvent
2105 if (*LastHead
== IPSEC_ESP_PROTOCOL
) {
2107 // Process the esp ipsec header of the inbound traffic.
2109 return IpSecEspInboundPacket (
2122 // The other protocols are not supported.
2124 return EFI_UNSUPPORTED
;
2128 This fucntion processes the output traffic with IPsec.
2130 It protected the sending packet by encrypting it payload and inserting ESP/AH header
2131 in the orginal IP header, then return the IpHeader and IPsec protected Fragmentable.
2133 @param[in] IpVersion The version of IP.
2134 @param[in, out] IpHead Point to IP header containing the orginal IP header
2135 to be processed on input, and inserted ESP/AH header
2137 @param[in, out] LastHead The Last Header in IP header.
2138 @param[in, out] OptionsBuffer Pointer to the options buffer.
2139 @param[in, out] OptionsLength Length of the options buffer.
2140 @param[in, out] FragmentTable Pointer to a list of fragments to be protected by
2141 IPsec on input, and with IPsec protected
2143 @param[in, out] FragmentCount Number of fragments.
2144 @param[in] SadEntry Related SAD entry.
2145 @param[out] RecycleEvent Event for recycling of resources.
2147 @retval EFI_SUCCESS The operation is successful.
2148 @retval EFI_UNSUPPORTED If the IPSEC protocol is not supported.
2152 IpSecProtectOutboundPacket (
2154 IN OUT VOID
*IpHead
,
2155 IN OUT UINT8
*LastHead
,
2156 IN OUT VOID
**OptionsBuffer
,
2157 IN OUT UINT32
*OptionsLength
,
2158 IN OUT EFI_IPSEC_FRAGMENT_DATA
**FragmentTable
,
2159 IN OUT UINT32
*FragmentCount
,
2160 IN IPSEC_SAD_ENTRY
*SadEntry
,
2161 OUT EFI_EVENT
*RecycleEvent
2164 if (SadEntry
->Id
->Proto
== EfiIPsecESP
) {
2166 // Process the esp ipsec header of the outbound traffic.
2168 return IpSecEspOutboundPacket (
2181 // The other protocols are not supported.
2183 return EFI_UNSUPPORTED
;