> For the complete documentation index, see [llms.txt](https://docs.cennso.com/components/fpp/3.2/llms.txt) (all documentation: [llms.txt](https://docs.cennso.com/llms.txt)). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.cennso.com/components/fpp/3.2/deployment-guides/ipsec.md).

# Set up IPsec

> [!IMPORTANT]
> IPsec support is an alpha feature and is not suitable for production deployments.

Fast Path Provider (FPP) 3.2.0 lets a Connectivity Gateway (CGW) terminate IPsec tunnels.
strongSwan 6.1 `charon` runs as a `VPPTool` next to Vector Packet Processing (VPP) and negotiates the tunnels with Internet Key Exchange (IKE).
Its `vpp_sswan` backend installs the Security Associations (SAs) in VPP, so VPP encrypts and decrypts the traffic in the Data Plane.

The integration supports:

- IKEv1 and IKEv2
- IPv4 and IPv6, for both the tunnel traffic and the underlay
- Mixed IP versions, IPv4 over IPv6 and IPv6 over IPv4, in route-based mode only
- NAT traversal (NAT-T), with [limitations](#limitations)
- Tunnel mode and transport mode
- Pre-shared keys and certificates
- Prometheus metrics for IKE_SAs, CHILD_SAs, and certificates

An IKE_SA is the authenticated channel between the two peers.
A CHILD_SA is the pair of SAs that carries the traffic.

## Prerequisites

Before you set up IPsec, make sure that you have:

- VPP Operator 3.2.0, upgraded as described in [3.1.0 -> 3.2.0](https://docs.cennso.com/components/fpp/3.2/releases/3.2.0.md#310---320)
- A `CGWDeployment` on the FPP 3.2.0 revision of the `cgw-generic` Composition

## Route-based and policy-based mode

`vpp_sswan` supports two modes.
A CHILD_SA selects the mode with its `if_id`.
The following table compares the two modes:

| Property | Route-based mode | Policy-based mode |
|---|---|---|
| CHILD_SA | `if_id_in`/`if_id_out` set, `policies = no` | No `if_id` |
| Traffic selection | Routes into a `VPPInterface` with **spec.ipsecTunnel** | Security Policy Database (SPD) entries on the underlay interface |
| Traffic that matches no tunnel | Leaves the CGW normally | Dropped on the underlay interface |
| IPv4 over IPv6 and IPv6 over IPv4 | Supported | Inbound traffic is dropped |
| Transport mode | Not supported | Supported |

Use route-based mode unless the peer requires otherwise.
Route-based mode avoids most of the [limitations](#limitations) of policy-based mode.
It also lets a routing protocol such as [Border Gateway Protocol (BGP)](https://docs.cennso.com/components/fpp/3.2/deployment-guides/bgp.md) run through the tunnel.

> [!CAUTION]
> In policy-based mode, once the first CHILD_SA is up, VPP drops all outbound traffic on the underlay interface unless the traffic matches a CHILD_SA. This includes the traffic of the CGW itself, for example routing protocols. After a VPP restart, VPP sends LAN traffic to the remote subnets without encryption until `charon` installs the first CHILD_SA.

## Create the VPPTool resources

Create the tools that negotiate the tunnels and export their metrics, and the Secret with the pre-shared key.

> [!CAUTION]
> Modifying a `VPPTool` object restarts all FPP pods that use it, which causes network downtime.

1. Create the `charon` `VPPTool` in the Core Cluster.
   The image ships with FPP and uses the FPP version as its tag:

   ```yaml
   apiVersion: fpp-manager.cennso.com/v1alpha1
   kind: VPPTool
   metadata:
     name: charon
   spec:
     image: registry.cennso.com/cennso/vpp-sswan:v3.2.0
     securityContext:
       privileged: true
     env:
     # Required for the ipsec-exporter VPPTool
     - name: FPP_CHARON_VICI_SOCKET
       value: /run/vici/charon.vici
     volumeMounts:
     # Required: vpp_sswan connects to VPP through the shared-memory API
     - name: shm
       mountPath: /dev/shm
     # Optional: SA byte and packet counters
     - name: run
       subPath: vpp
       mountPath: /run/vpp
     - name: charon-psk
       mountPath: /etc/swanctl/conf.d
       readOnly: true
     - name: vici
       mountPath: /run/vici
     volumes:
     - name: charon-psk
       secret:
         secretName: charon-psk
     - name: vici
       emptyDir:
         medium: Memory
     configFiles:
     - name: swanctl.conf
       canReload: true
   ```

   The following rules apply to the `charon` definition:

   - The container must be privileged, because the tool starts `charon` in the Linux Control Plane (LCP) network namespace.
   - `shm` and `run` are volumes of the FPP pod. Do not declare them in **spec.volumes**.
   - Keep secrets out of the `CGWDeployment`. Mount them as a Secret in `/etc/swanctl/conf.d`. Mount certificates and keys in `/etc/swanctl/x509` and `/etc/swanctl/private`.
   - With `canReload: true`, a change of `swanctl.conf` reloads the configuration without a restart of the pod.

2. Create the Secret with the pre-shared key in the namespace of the CGW:

   ```yaml
   apiVersion: v1
   kind: Secret
   metadata:
     name: charon-psk
     namespace: {CGW_NAMESPACE}
   type: Opaque
   stringData:
     psk.conf: |
       secrets {
         ike-peer {
           id-local = cgw-a
           id-remote = cgw-b
           secret = "{PRE_SHARED_KEY}"
         }
       }
   ```

3. (Optional) To export IPsec metrics, create the `ipsec-exporter` `VPPTool`.
   It reads the state of `charon` through the VICI socket in the shared `vici` volume:

   ```yaml
   apiVersion: fpp-manager.cennso.com/v1alpha1
   kind: VPPTool
   metadata:
     name: ipsec-exporter
   spec:
     image: registry.cennso.com/cennso/ipsec-exporter:v1.8.0-cgw-1.10.0
     command:
     - /ipsec-prometheus-exporter
     - -enable-cert-metrics
     - -enable-conn-metrics
     - -server-port
     - "9536"
     - -vici-network
     - unix
     - -vici-address
     - /run/vici/charon.vici
     volumeMounts:
     - name: vici
       mountPath: /run/vici
       readOnly: true
   ```

The Core Cluster now has the tools and the Secret that the `CGWDeployment` refers to.

## Configure the CGWDeployment

Add the IPsec configuration to a `CGWDeployment`.

1. Write a `CGWDeployment` manifest with the IPsec configuration.
   The following example sets up a route-based tunnel between two local area networks (LANs).
   The tunnel connects `10.81.0.0/24` behind CGW `cgw-a` with `10.82.0.0/24` behind the peer at `10.80.0.2`:

   ```yaml
   apiVersion: fpp.cennso.com/v1alpha1
   kind: CGWDeployment
   metadata:
     name: cgw-a
   spec:
     version: 3.2.0
     connectionSecretRef:
       name: test-core-cluster
       namespace: cennso-infra
     ...
     # required for metrics scraping
     cnfName: cgw

     vppTools:
     - name: charon
     - name: ipsec-exporter

     ipsec:
       metricsEnabled: true

     vppInterfaces:
     # Underlay: IKE and ESP
     - ifName: underlay
       attachToNetwork: underlay-network
       memif:
         role: slave
       tableName: underlay
       mtu: 1500
       ips:
       - 10.80.0.1/24
     - ifName: lan
       attachToNetwork: lan-network
       memif:
         role: slave
       tableName: lan
       ips:
       - 10.81.0.1/24
     # charon sends IKE through the LCP mirror of the underlay
     - ifName: lcp0
       lcp:
         attachTo: underlay
         hostIfName: lcp0
     # Route-based tunnel interface
     - ifName: vti
       ipsecTunnel:
         instance: 1
       tableName: lan
       mtu: 1399
       ips:
       - 10.90.0.1/30

     routingTables:
       underlay:
         id: 80
         addressFamily: IPv4
       lan:
         id: 81
         addressFamily: IPv4
         routes:
         # The route selects which traffic goes into the tunnel
         - cidr: 10.82.0.0/24
           nextHopInterface: vti

     vppConfigs:
     - spec:
         toolConfigs:
         - name: charon
           configFiles:
           - name: swanctl.conf
             content: |
               include conf.d/*.conf

               connections {
                 to-cgw-b {
                   version = 1
                   local_addrs = 10.80.0.1
                   remote_addrs = 10.80.0.2
                   dpd_delay = 30s
                   keyingtries = 0
                   proposals = aes256-sha256-modp2048
                   local {
                     auth = psk
                     id = cgw-a
                   }
                   remote {
                     auth = psk
                     id = cgw-b
                   }
                   children {
                     # Route-based: the routes into vti select the traffic
                     # of the tunnel, so the traffic selectors cover all traffic.
                     bgp {
                       esp_proposals = aes256-sha256
                       local_ts = 0.0.0.0/0
                       remote_ts = 0.0.0.0/0
                       if_id_in = 1
                       if_id_out = 1
                       policies = no
                       start_action = start
                       dpd_action = restart
                       close_action = restart
                       # Short lifetimes for testing; use longer values in production.
                       rekey_time = 4m
                       life_time = 5m
                       rand_time = 1m
                     }
                   }
                 }
               }
   ```

2. Apply the `CGWDeployment` on the Management Cluster:

   > [!CAUTION]
   > If you apply this configuration to an existing CGW, the CGW pods restart, and traffic through the CGW stops until the pods are ready.

   ```bash
   kubectl apply -f {CGW_DEPLOYMENT_FILE}
   ```

The CGW pod starts with the `tool-charon` container, and `charon` starts the tunnel.

### The ipsecTunnel interface

A `VPPInterface` with **spec.ipsecTunnel** creates a VPP IPsec tunnel interface.
`vpp_sswan` attaches the SAs of a CHILD_SA to the interface whose **spec.ipsecTunnel.instance** equals the `if_id` of the CHILD_SA.

The tunnel interface has the following requirements:

- **spec.ipsecTunnel.instance** must be from `1` to `16383` and unique in the CGW. If two `VPPInterface` resources request the same instance, the oldest one uses it, and the others stay not ready with a Warning event.
- The interface needs an IP address of each IP version that the tunnel carries. VPP drops decrypted packets of an IP version that is not enabled on the interface.
- Set the maximum transmission unit (MTU) at least 101 bytes below the MTU of the underlay, or 121 bytes for an IPv6 underlay. Otherwise VPP drops large packets after encryption.
- The interface and the LAN can use a different table than the underlay. VPP sends the Encapsulating Security Payload (ESP) packets in the table of the underlay.
- Without an established CHILD_SA, the interface drops all traffic.
- The route to the IKE address of the peer must not go through the tunnel interface.

### swanctl.conf rules

Follow these rules in `swanctl.conf`:

- Set `local_addrs` to the underlay address. `vpp_sswan` uses it to find the interface and table of the SAs.
- In route-based mode, set the following CHILD_SA options:
  - `if_id_in` and `if_id_out` to the same value
  - `policies = no`
  - `start_action = start`
- Use one CHILD_SA for each `if_id`.
- For policy-based mode, omit `if_id_in`, `if_id_out`, and `policies`. Add a route to the remote LAN through the underlay interface. VPP routes decrypted packets in the table of the underlay, so also add a route in that table back to the LAN interface.
- `charon` does not install routes. Configure them with **spec.routingTables**.
- Run only one `charon` per CGW. When `charon` starts, it removes all IPsec objects from VPP. For this reason, do not create IPsec objects with `beforeCommands` or `afterCommands` of a `VPPConfig`.

## IPsec metrics

Set **spec.ipsec.metricsEnabled** to `true` to expose the `ipsec-exporter` metrics on port `9536` of the CGW Service.
The `fpp-support` CGW `ServiceMonitor` scrapes this port when **spec.cnfName** is `cgw`.

The `ipsec-exporter` metrics are the same as in CGW 1.x.
For the list of metrics, see [IPsec Exporter metrics](https://docs.cennso.com/components/cgw/1.12/observability/metrics.md#ipsec-exporter) in the CGW documentation and [IPsec metrics](https://docs.cennso.com/components/fpp/3.2/observability/metrics.md#ipsec-metrics).

### CGW 1.x Grafana dashboard

The IPsec metrics of an FPP CGW work with the **CGW Overview** Grafana dashboard of the CGW 1.x `cgw-support` chart.
The CGW `ServiceMonitor` adds the `app: cgw` and `release: {POD_NAME}` labels that the dashboard filters on, so its IPsec panels show FPP CGW tunnels without changes.
For a description of the panels, see the [CGW Grafana dashboard](https://docs.cennso.com/components/cgw/1.12/observability/grafana-dashboard.md) documentation.

## Restart behavior

If VPP or `charon` restarts, the tool starts a new `charon` that clears the old SAs and negotiates all tunnels again.
The tunnels are down until `charon` installs the new CHILD_SAs.
During this time, route-based tunnels drop the LAN traffic.
In policy-based mode, the LAN traffic can leave unencrypted after a VPP restart, until `charon` installs the first CHILD_SA.

A CHILD_SA without `start_action = start` stays down until the peer initiates it again.

## Limitations

IPsec support in FPP 3.2.0 has the following limitations:

- Use each local IKE address on only one VPP interface. If two interfaces have the address, `vpp_sswan` uses the first one.
- VPP does not check the traffic selectors of decrypted traffic. If the underlay network is not trusted, add an input `VPPACL` on the IPsec tunnel interface that permits only the peer subnets. This applies to route-based mode.
- NAT-T works only if the NAT in front of the peer keeps the peer's ports 500 and 4500, for example with a static port mapping. VPP always sends ESP-in-UDP packets to port 4500 of the peer.
- Each stop of the CGW pod logs a `FailedPreStopHook` warning event for the `ipsec-exporter` container, because its image has no shell. The event has no effect on the pod.
- In policy-based mode:
  - Inbound IPv4 over IPv6 and IPv6 over IPv4 traffic does not reach the LAN, because VPP drops it. Use route-based mode for these combinations.
  - VPP does not drop unencrypted inbound packets that match a protected subnet.
  - Once the first CHILD_SA is up, VPP drops all other outbound traffic on the underlay interface, including the CGW's own traffic. Send other traffic through an interface without IKE.
  - VPP drops ESP packets that arrive as IP fragments. As a workaround, add `set interface reassembly {{ .Ifs.underlay.Name }} ip4` to the `afterCommands` of a `VPPConfig`.
  - If a packet with the Don't Fragment (DF) bit is too large after encryption, VPP drops it. The sender gets no Internet Control Message Protocol (ICMP) message. Clamp the TCP maximum segment size (MSS) on the LAN side, or set `copy_df = no` for the CHILD_SA.
  - LAN traffic that is itself IPsec, such as ESP, Authentication Header (AH), or IKE on UDP port 500 or 4500, bypasses the tunnel.
  - Transport mode does not support NAT-T over IPv6. Use tunnel mode if NAT-T is necessary.

## Verification

Check the SAs in the `tool-charon` container:

```bash
kubectl -n {CGW_NAMESPACE} exec {CGW_POD} -c tool-charon -- swanctl --list-sas
```

Sample output for the tunnel of the `CGWDeployment` example:

```text
to-cgw-b: #1, ESTABLISHED, IKEv1, 3ddf3caa0c3b9b6b_i* cf26e6037833567a_r
  local  'cgw-a' @ 10.80.0.1[500]
  remote 'cgw-b' @ 10.80.0.2[500]
  AES_CBC-256/HMAC_SHA2_256_128/PRF_HMAC_SHA2_256/MODP_2048
  established 9662s ago, rekeying in 4238s
  bgp: #49, reqid 1, INSTALLED, TUNNEL, ESP:AES_CBC-256/HMAC_SHA2_256_128
    installed 120s ago, rekeying in 65s, expires in 180s
    in  ce69137d (-|0x00000001),    448 bytes,     4 packets
    out c18ab81b (-|0x00000001),    352 bytes,     4 packets
    local  0.0.0.0/0
    remote 0.0.0.0/0
```

The IKE_SA must be `ESTABLISHED`, and the CHILD_SA must be `INSTALLED`.

Check that VPP attached the SAs to the tunnel interface:

```bash
kubectl -n {CGW_NAMESPACE} exec {CGW_POD} -c fpp -- vppctl show ipsec protect
```

Sample output for the tunnel interface `vti` of the same tunnel:

```text
vti flags:[]
 output-sa:
  [1] sa 98 (0x62) spi 3247093787 (0xc18ab81b) protocol:esp flags:[anti-replay tunnel no-algo-no-drop ]
 input-sa:
  [0] sa 97 (0x61) spi 3462992765 (0xce69137d) protocol:esp flags:[anti-replay tunnel inbound ]
```

The tunnel interface must list an output SA and an input SA with the Security Parameter Indexes (SPIs) that `swanctl --list-sas` shows.

If the tunnel interface does not exist yet, the `charon` log shows `interface ipsec<if_id> not found, its SAs wait for it`.
`vpp_sswan` attaches the SAs as soon as the interface appears.
