> For the complete documentation index, see [llms.txt](https://docs.cennso.com/components/cgw/1.12/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/cgw/1.12/tutorials/06-connect-two-cgws.md).

# Connect two CGWs

The previous tutorials each configure one side of a connection against a peer
that exists elsewhere. This one builds both sides: two CGW releases in one
Kubernetes cluster, connected by a certificate-authenticated, policy-based
IPsec tunnel, with an eBGP session running inside that tunnel that exchanges a
hundred routing prefixes, and with every exporter enabled.

It is a self-contained playground. Nothing in it touches the cluster network —
the tunnel endpoints are dummy interfaces inside the pods, and the routes the
two BIRD instances exchange never reach a pod's routing table.

```
  namespace cgw-test

  +-------------------------+                   +-------------------------+
  | cgw-a            AS65001|                   | cgw-b            AS65002|
  |  dum0 198.18.1.1/32     |                   |  dum0 198.18.2.1/32     |
  |  strongSwan (responder) |<== ESP/UDP4500 ===| strongSwan (initiator)  |
  |  BIRD                   |<--- eBGP/179 ---->| BIRD                    |
  |  eth0 <pod IP>          |   (in the tunnel) |  eth0 <pod IP>          |
  |                         |                   |                         |
  |  ipsec-exporter   :9536 |                   |  ipsec-exporter   :9536 |
  |  conntrack-exporter:9371|                   |  conntrack-exporter:9371|
  |  ping-exporter    :9427 |                   |  ping-exporter    :9427 |
  |  bird-exporter    :9324 |                   |  bird-exporter    :9324 |
  |  pcap (eth0) -> /data/  |                   |                         |
  +-------------------------+                   +-------------------------+
             ^                                              |
             |                                              |
             +-- svc cgw-a-ipsec (ClusterIP, UDP 500/4500) -+
```

## Files

The snippets below are excerpts. Download the complete files:

- [values-site-a.yaml](https://docs.cennso.com/api/assets/components/cgw/1.12/assets/tutorial-two-cgw/values-site-a.yaml) — the
  responder, and the side that carries the annotated comments
- [values-site-b.yaml](https://docs.cennso.com/api/assets/components/cgw/1.12/assets/tutorial-two-cgw/values-site-b.yaml) — the
  initiator, a mirror of site A
- [mkcerts.sh](https://docs.cennso.com/api/assets/components/cgw/1.12/assets/tutorial-two-cgw/mkcerts.sh) — builds the throwaway
  PKI and the Secrets that carry it into the releases
- [values-support.yaml](https://docs.cennso.com/api/assets/components/cgw/1.12/assets/tutorial-two-cgw/values-support.yaml) — the
  optional `cgw-support` release for the ServiceMonitor

## Prerequisites

- A Kubernetes cluster. One node is enough, and no Multus or host networking is
  needed.
- Pods may request the `NET_ADMIN` capability. Nothing here runs privileged or
  mounts a host path, so a restricted PodSecurity level is fine as long as
  `NET_ADMIN` is allowed.
- `helm`, `kubectl` and `openssl` 3.x.
- Pull access to `registry.cennso.com/cennso`, the registry that also serves
  the chart. Both values files reference the image pull secret
  `cennso-pull-secret`, which has to exist in the namespace before the pods
  start.

No monitoring stack is needed to follow this tutorial — every check below reads
the metrics directly from the exporters. Collecting them in Prometheus and
viewing them in Grafana is an
[optional last step](#optional-scrape-it-with-prometheus-and-look-at-the-dashboard)
with prerequisites of its own.

## Create the namespace and the pull secret

Both releases go into one namespace:

```sh
export NS=cgw-test
kubectl create namespace "$NS"

kubectl create secret docker-registry cennso-pull-secret \
    --docker-server=registry.cennso.com \
    --docker-username="$REGISTRY_USER" \
    --docker-password="$REGISTRY_PASSWORD" \
    -n "$NS"
```

## Build the PKI

The two CGWs authenticate the IPsec connection with X.509 certificates rather
than with a pre-shared key. That makes certificate handling observable: the
ipsec-exporter reports `strongswan_cert_valid` and
`strongswan_cert_expire_secs` for what strongSwan has loaded, so certificate
validation and an approaching expiry can be checked from the metrics. A
pre-shared key neither validates nor expires, and strongSwan loads no
certificate at all.

`mkcerts.sh` builds one self-signed root and one end-entity certificate per
site, signed by that root. The extended key usage is what makes a certificate
usable for IKE:

```sh
openssl x509 -req -in "${site}.csr" -CA ca.pem -CAkey ca-key.pem \
    -days "${LEAF_DAYS}" -out "${site}.pem" \
    -extfile <(printf '%s\n' \
        "basicConstraints=critical,CA:FALSE" \
        "keyUsage=critical,digitalSignature" \
        "extendedKeyUsage=1.3.6.1.5.5.7.3.17" \
        "subjectAltName=DNS:${site}.${DOMAIN}")
```

It writes the certificates and a `secrets.yaml` into `pki/`, which has to be
applied before the releases are installed — the values files reference these
Secrets by name:

```sh
bash ./mkcerts.sh
kubectl apply -n "$NS" -f pki/secrets.yaml
```

The whole Secret is mounted as a directory, so every key in it becomes a file
name that strongSwan sees. That is why the `leftcert=` and `: ECDSA` lines
further down name these exact files.

>**NOTE:** The site certificates are valid 30 days by default, so that
>`strongswan_cert_expire_secs` reports a number worth reading instead of a
>decade. Override it with `LEAF_DAYS`. Once they expire, the tunnel between the
>sites stays down, and the *IPSec X509 Certificates* row of the dashboard shows
>them as invalid.

To renew the certificates, reissue them and apply the Secrets again. The
kubelet updates the mounted files in the running pods within about a minute.
strongSwan reads them only once, so then have it load them on both sites:

```sh
bash ./mkcerts.sh --force
kubectl apply -n "$NS" -f pki/secrets.yaml
# after about a minute, once the mounted files are updated:
for site in a b; do
    kubectl exec -n "$NS" "deploy/cgw-${site}" -c ipsec -- ipsec rereadall
    kubectl exec -n "$NS" "deploy/cgw-${site}" -c ipsec -- ipsec reload
done
```

`ipsec rereadall` loads the private key and the CA, and `ipsec reload` adds the
connections again, which loads the site certificate. Established SAs stay up
and no pod restarts.

## Install site A, the responder

```sh
helm install cgw-a oci://registry.cennso.com/charts/cgw \
    --version "$VERSION" -n "$NS" -f values-site-a.yaml
```

Site A waits for its peer (`auto=add`, `right=%any`), so it does not need to
know where site B runs:

```yaml
conn site-b
    also=sts-base
    auto=add
    left=%any
    leftcert=site-a.pem
    leftid="CN=site-a.cgw-test"
    leftsubnet=198.18.1.1/32
    right=%any
    rightid="CN=site-b.cgw-test"
    rightsubnet=198.18.2.1/32
```

The tunnel endpoints are the two pod IPs, while the protected subnets are the
dummy `/32` addresses. Keeping the pod IPs out of the traffic selectors is what
stops the XFRM policies from capturing the pod's own cluster traffic — DNS, IKE
and the metric scrapes all stay outside the tunnel.

An init container creates that dummy interface and the route that steers
traffic for the peer endpoint into the IPsec policy. `NET_ADMIN` is enough; no
privileged container and no host mount, unlike the
[route-based setup](https://docs.cennso.com/components/cgw/1.12/tutorials/04-route-based-vpn.md):

```yaml
additionalInitContainers:
  - name: init-endpoint
    image: registry.cennso.com/cennso/nettools:v1.19.1
    resources:
      limits:
        cpu: 50m
        memory: 64Mi
    securityContext:
      capabilities:
        add: ["NET_ADMIN"]
    command:
      - sh
      - -c
      - |
        set -ex
        ip link add dum0 type dummy
        ip addr add 198.18.1.1/32 dev dum0
        ip link set dum0 up
        ip route add 198.18.2.1/32 \
            via "$(ip -4 route show default | awk '{print $3; exit}')" \
            dev eth0 src 198.18.1.1
```

Site A also creates the ClusterIP service that site B dials, and enables the
`iptables` container. That ruleset is not there to filter — the chain policies
stay `ACCEPT`. Current kernels do not track a network namespace until a rule
actually asks for connection tracking, so without it the conntrack-exporter
would come up and report an empty table.

## Install site B, the initiator

```sh
helm install cgw-b oci://registry.cennso.com/charts/cgw \
    --version "$VERSION" -n "$NS" -f values-site-b.yaml
```

Site B is the mirror image, with two differences. It dials out as soon as
strongSwan starts, and it addresses site A through the service name rather than
a pod IP, which survives a pod restart:

```yaml
conn site-a
    also=sts-base
    auto=start
    left=%any
    leftcert=site-b.pem
    leftid="CN=site-b.cgw-test"
    leftsubnet=198.18.2.1/32
    right=cgw-a-ipsec
    rightid="CN=site-a.cgw-test"
    rightsubnet=198.18.1.1/32
```

Reaching site A through a ClusterIP means reaching it through a DNAT.
strongSwan sees that as a NAT and switches to UDP encapsulation; `forceencaps=yes`
in the shared `sts-base` section makes that unconditional, so the data path
also works on CNIs that do not forward plain ESP.

>**NOTE:** `right=cgw-a-ipsec` is a short name, resolved by the pod's search
>domain within its own namespace. It therefore depends on site A being
>installed under the release name `cgw-a` in the same namespace. Use
>`cgw-a-ipsec.<namespace>.svc.cluster.local` if you split the two releases up.

Both sides run an eBGP session between the tunnel endpoints, so the BGP traffic
is carried by the IPsec SA and doubles as a payload generator for it. Each side
originates one documentation prefix from RFC 5737, and the kernel protocol
exports nothing:

```
protocol kernel {
    export none;
}

protocol bgp site_a {
    local as 65002;
    source address 198.18.2.1;
    neighbor 198.18.1.1 as 65001;
    # the endpoints are /32s reachable through the tunnel, not on-link
    multihop 2;
    hold time 30;
    import all;
    export where proto = "originated" || proto = "bulk";
}
```

Site B originates 100 more `/32`s from a second static protocol named `bulk`.
A session carrying a single prefix leaves the prefix counters at 1, which says
little about whether they work; with `bulk` the two directions are asymmetric —
101 exported here, 1 imported — so `bird_protocol_prefix_import_count` and
`bird_protocol_prefix_export_count` have something to report and it stays
obvious which direction is which.

## Verify

The tunnel comes up within a few seconds. Site B initiates, so its status is
the more interesting one:

```sh
kubectl exec -n "$NS" deploy/cgw-b -c ipsec -- ipsec statusall
```

Expect `site-a[1]: ESTABLISHED` and an installed CHILD_SA between
`198.18.2.1/32` and `198.18.1.1/32`. With certificate authentication the line
above it names both DNs — `CN=site-b.cgw-test` and `CN=site-a.cgw-test` —
instead of the `@site-b`/`@site-a` identities a PSK setup would show.

What strongSwan loaded of the PKI:

```sh
kubectl exec -n "$NS" deploy/cgw-b -c ipsec -- swanctl --list-certs
```

The data path, end to end through the tunnel:

```sh
kubectl exec -n "$NS" deploy/cgw-b -c debug -- ping -c3 -I 198.18.2.1 198.18.1.1
```

The BGP session and what it carries:

```sh
kubectl exec -n "$NS" deploy/cgw-b -c bird -- birdc show protocols
kubectl exec -n "$NS" deploy/cgw-b -c bird -- birdc show route

# 101 exported towards the peer here, 1 imported from it
kubectl exec -n "$NS" deploy/cgw-b -c bird -- birdc show protocols all site_a
```

`site_a` reaches state `Established`, and `show route` lists the locally
originated prefixes next to `203.0.113.0/24` learned from site A. None of them
appear in `ip route` inside the pod, which is what `export none` is for.

Every exporter can be scraped from inside the pod, through the `debug`
container that shares its network namespace:

```sh
# tunnel liveness as a metric
kubectl exec -n "$NS" deploy/cgw-b -c debug -- \
    curl -s localhost:9427/metrics | grep ping_

# strongSwan SAs, connections, certificate lifetimes
kubectl exec -n "$NS" deploy/cgw-b -c debug -- \
    curl -s localhost:9536/metrics | grep -E '^strongswan_(sa|conn|cert)_'

# conntrack of the pod network namespace
kubectl exec -n "$NS" deploy/cgw-b -c debug -- \
    curl -s localhost:9371/metrics | grep node_nf_conntrack

# BGP session state and prefix counts
kubectl exec -n "$NS" deploy/cgw-b -c debug -- \
    curl -s localhost:9324/metrics | grep -E 'bird_protocol_(up|prefix)'
```

To watch the encrypted packets on the wire:

```sh
kubectl exec -n "$NS" deploy/cgw-b -c debug -- tcpdump -ni eth0 udp port 4500
```

Site A also records its own traffic with the PCAP collector: `dumpcap` writes
`eth0` into a ring of two 10 MB files below `/data/`, named after
`pcap.env.FILENAME`. There is no `rclone` to upload them, so they stay in the
pod. The `debug` container mounts the same directory read-only, so that is
where to list them and copy them out:

```sh
kubectl exec -n "$NS" deploy/cgw-a -c debug -- ls -l /data/

# kubectl cp needs a pod name rather than the deployment
pod="$(kubectl get pod -n "$NS" -l release=cgw-a -o jsonpath='{.items[0].metadata.name}')"
kubectl cp -n "$NS" -c debug "${pod}:/data/" ./cgw-a-pcap/
```

The captures show IKE on UDP/500 and UDP/4500 in the clear, and the ESP that
carries BGP and the ping probes encapsulated in UDP/4500, encrypted.

## Optional: scrape it with Prometheus and look at the dashboard

Everything above reads the metrics straight from the exporters, so the tunnel
can be verified without any monitoring stack. To collect them continuously and
to see them in Grafana, install the `cgw-support` chart on top. It needs more
of the cluster than the two CGW releases do:

- The **Prometheus Operator** CRDs, for the `ServiceMonitor`, plus a Prometheus
  instance whose ServiceMonitor selector picks this one up.
- The **Grafana Operator** and a Grafana instance, for the
  [CGW dashboard](https://docs.cennso.com/components/cgw/1.12/observability/grafana-dashboard.md). The dashboard is a
  `GrafanaDashboard` custom resource, and it is disabled in
  `values-support.yaml` — set `dashboard.enabled: true` and match
  `dashboard.instanceSelector` to the Grafana it should land in.

```sh
helm install cgw-support oci://registry.cennso.com/charts/cgw-support \
    --version "$VERSION" -n "$NS" -f values-support.yaml
```

The ServiceMonitor covers all five exporter ports and is scoped to this
namespace:

```yaml
prometheus:
  servicemonitor:
    enabled: true
    namespaceSelector:
      # `any` wins over `matchNames`, so it has to be turned off explicitly
      any: false
      matchNames:
        - cgw-test
    selector:
      matchLabels:
        app: cgw
```

Once Prometheus scrapes the two pods, this deployment feeds every row of the
dashboard: the two `dum0` addresses and the second, unused dummy interface on
site A give the `CGW_INTERFACES` variable something to select and the
*Network Throughput* row something to repeat over, the certificates populate
the *IPsec X509 Certificates* row, and the asymmetric BGP session fills the
*Imported / exported prefixes* panel.

>**NOTE:** Where the cluster already runs a ServiceMonitor that selects
>`app: cgw`, both will scrape these pods and every shared port is reported
>twice. The samples differ in their `job` label, so they do not overwrite each
>other, but they do double the series. Narrow the `selector` — by `release`,
>for instance — to keep the two monitors apart.

## Teardown

```sh
helm uninstall -n "$NS" cgw-b
helm uninstall -n "$NS" cgw-a
kubectl delete namespace "$NS"
```

## Troubleshooting

- **`site-a` never establishes.** Check that site B resolves the peer:
  `kubectl exec -n "$NS" deploy/cgw-b -c debug -- nslookup cgw-a-ipsec`. The
  name is fixed in `values-site-b.yaml`, so it breaks if site A is installed
  under another release name or into another namespace.
- **IKE completes, but the ping fails.** Usually the route from the init
  container is missing, for example because the pod has no default route on
  `eth0`. Compare `ip route get 198.18.1.1` inside the pod with the XFRM policy
  from `ip xfrm policy`.
- **The conntrack metrics stay empty.** The `iptables` container has to be
  enabled; without a rule that asks for connection tracking, the namespace is
  not tracked at all.
- **NetworkPolicies** in the namespace have to allow UDP 500 and 4500 between
  the two pods, in both directions.

## Where to go next

Each side of this deployment is one of the earlier tutorials, combined:

- [Set up a VPN connection with IPsec](https://docs.cennso.com/components/cgw/1.12/tutorials/02-setup-vpn-ipsec.md) explains the
  policy-based `ipsec.conf` this tutorial mirrors on both sides.
- [Set up a certificate-based VPN](https://docs.cennso.com/components/cgw/1.12/tutorials/03-setup-certificate-vpn.md) explains the
  Secrets that `mkcerts.sh` generates here.
- [Secure CGW using a firewall](https://docs.cennso.com/components/cgw/1.12/tutorials/05-firewall.md) covers the `iptables` values
  that this deployment uses to engage conntrack.
- [Monitoring configuration](https://docs.cennso.com/components/cgw/1.12/configuration/monitoring.md) documents the
  ping-exporter configuration, and
  [Metrics](https://docs.cennso.com/components/cgw/1.12/observability/metrics.md) lists what the other exporters
  publish.
