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

# Secure CGW using a firewall

To secure the CGW pod against unwanted traffic, use `iptables` as a firewall. This is especially important if a public IP is attached to the pod.

## Concepts

Below are some basics of the inner workings of `iptables`.

The explanation of the syntax and semantics of `iptables` rules are out of the scope of this documentation. Consider some of the following resources if you are not familiar with the rules yet:

- Suehring, Steve. Linux Firewalls : Enhancing Security with Nftables and Beyond. 4. ed. 2015.
- [Netfilter project](https://www.netfilter.org/documentation/index.html)
- [Ubuntuusers wiki (German)](https://wiki.ubuntuusers.de/iptables2/)
- [Arch Linux wiki](https://wiki.archlinux.org/title/Iptables)

Further, you should get a basic understanding of the basic working of `iptables` before continuing with firewall configuration, including tables, chains, and rules.

### Available tables

Refer to this [diagram from the Arch Wiki](https://wiki.archlinux.org/title/Iptables#Basic_concepts) to see the flow and used tables of `iptables`.

If not considering NATting, the tables of importance are `INPUT`, `OUTPUT`, and `FORWARD`.

The `INPUT` and `OUTPUT` tables are used for the traffic coming from and going into process on the machine itself. Therefore, for every software running in the pod, the rules for this specific software must be added.

The `FORWARD` table is only used for traffic routed over this pod or node.

>**WARNING:** Protocols like VXLAN create a new device in the pod but use the underlying device for the encapsulated traffic itself. Because of this, the VXLAN traffic must be allowed on the underlying interface and the traffic from and to the VXLAN interface must be considered separately.

This also applies for other overlay protocols or encapsulations including IPSEC.

```
              +----------+            +------------+
              |          |            |            |
  +-------->  |   eth0   |  +------>  |   vxlan0   |
              |          |            |            |
              +----------+            +------------+
```

### Dropping vs rejecting traffic

There are two different ways of blocking traffic: dropping or rejecting.

In the first case, the traffic is just silently dropped. In the second case, the firewall sends an ICMP message with a reason why the target is not reachable.

Concerning [RFC1122](https://tools.ietf.org/html/rfc1122#page-69), endpoints should send error messages when possible. Also, debugging inside the cluster gets easier if it is clear whether a port is blocked or the service behind it is not running.

On the contrary though, more traffic is created when rejecting packets and it has been used in the past for attacking other hosts (DDOS).

Therefore, it is advised to use rejection inside a network perimeter, where rouge services are not expected to be the rule but an exception and use dropping the edges to the public internet.

Setting policies and [ICMP message types](#rejecting-traffic-with-a-specific-icmp-message) are described below.

## Enable iptables firewall configuration

To enable `iptables`, set the following values in your CGW configuration:

```yaml
iptables:
  enabled: true  # default is false
  ipv4Rules: |
    <add your rules here as described below>
  ipv6Rules: |
    <add your rules here as described below>
```

## Configure `iptables` rules

The rules must match the rules of the [iptables-save](https://linux.die.net/man/8/iptables-save) format, which is used for the above mentioned file.

Common parts of the configuration are explained below.

Most rules can be applied to the configuration of both IPv4 and IPv6, if not marked otherwise.

>**NOTE:** You must configure the firewall for both protocols to be effective!

### Basic format

The format consists basically of three parts in a block, where each block can repeat.

The first part is the declaration of the table to be used in the format `*<tablename>`.

The second part are the rules themselves, each in a single line. These match the syntax you would normally use on the command line. The parameter of the table MUST be omitted though in the rules, because it is already defined by the first part.

The third part is the `COMMIT` statement, to commit the changes of the configuration.

These blocks can be repeated for different tables.

An example of a rules file:

```
*filter     <-- *table describes the iptables table to use
-A INPUT -i lo -j ACCEPT  <-- command of changing rules equivalent to the one in the cli
COMMIT    <-- commits this table

*mangle   <-- use `mangle` table
-A POSTROUTING -p tcp --tcp-flags SYN,RST SYN -o inet0 -j TCPMSS --set-mss 1250 <-- another rule
COMMIT <-- commits this table
```

## Useful configuration blocks by example

### Set the default policies of the chain

To set the default policies of the firewalling chains, you can add the following:

```
*filter
## Block all traffic silently as default policy
## Take care because this can cause harm if wrongly configured
-P INPUT DROP
-P FORWARD DROP
-P OUTPUT DROP
COMMIT
```

Possible options are `ACCEPT` and `DROP`.

As the name *default policy* might suggest, for every packet for which none of the defined rules match, the default policy is applied and the packet either is accepted or dropped.

Because of erroneous human behaviour while writing rules, it is advised to set the default policy to `DROP` for increased security. Be careful with this option during development to not lock yourself out.

For readability it is advised to explicitly reject or drop unwanted traffic due to rules.

### Allow loopback traffic

To allow loopback traffic from local services, add the following lines to the configuration:

```
## Allows all loopback (lo) traffic and drop all traffic to 127/8 that doesn't use lo
-A INPUT -i lo -j ACCEPT
-A INPUT ! -i lo -d 127.0.0.0/8 -j REJECT
```

For IPv6 it is:

```
## Allows all loopback (lo) traffic and drop all traffic to 127/8 that doesn't use lo
-A INPUT -i lo -j ACCEPT
-A INPUT ! -i lo -d ::1 -j REJECT
```

### Allow traffic from Calico network

For pods on a Kubernetes cluster using Calico you could add the following to allow traffic from the main interface:

```
## Allow all traffic from and to Calico network
-A INPUT -i eth0 -j ACCEPT
-A OUTPUT -o eth0 -j ACCEPT
```

If you want to close the traffic further, you could also add further restrictions on protocols or IP addresses (see below).

For general separation of namespaces and services, it might be useful to look into Calico native policy enforcement.

### Allow traffic from and to your VTI interfaces

I you use *route-based VPN* with CGW, you create a virtual terminal interface to route the traffic to, you want to tunnel.

The following rules will accept all traffic coming from and going to the interfaces, as well as routing:

```
## allow incoming and outgoing traffic on vti interface
-A INPUT -i vti42 -j ACCEPT
-A OUTPUT -o vti42 -j ACCEPT
## allow routing on vti42 only if gre is not used
-A FORWARD -i vti42 -j ACCEPT
-A FORWARD -o vti42 -j ACCEPT
```

If you just need to have ICMP traffic from and to the CGW allowed for debugging and have a dedicated interface for connection to the connected service, for example through VXLAN, you can restrict the rules further:

```
## allow incoming and outgoing traffic on vti interface
-A INPUT -i vti42 -p icmp -j ACCEPT
-A OUTPUT -o vti42 -p icmp -j ACCEPT
## allow routing on vti42 only if gre is not used
-A FORWARD -i vti42 -o service0 -j ACCEPT
-A FORWARD -o vti42 -i service0 -j ACCEPT
```

You can even limit the traffic to specific protocols, ports, or IP addresses (see below).

### Allow ICMP traffic on public interfaces

On some deployment of CGW, there will be an interface attached, which provides a public IP address.

To allow ICMP traffic to and from the interface, add the following:

```
## allow icmp on inet0 (the interface with the public ip address)
-A INPUT -i inet0 -j ACCEPT -p icmp
-A OUTPUT -o inet0 -j ACCEPT -p icmp
```

### Allow IPSEC traffic

This scenario assumes that an interface with a public IP address is used (see above).
If this is not the case, either the interfaces must be changed or the rules can be omitted, if all traffic on the Calico interface is allowed.

IPSEC can use three different kinds of traffic in normal setups:

- ESP protocol, which is mostly used between two sites for the data traffic
- UDP port 500, which is used for IKE negotiations and NAT detection
- UDP port 4500, which is used for IKE and data when a NAT is detected or UDP encapsulation is enforced.

In cases where ESP is known to be not working or no NATs exists, either one or the other rule can be removed.

```
## add rules for ipsec on external interface
# Only allow IPSEC traffic from and to the other side gateway
# ESP
-A INPUT  -p esp -i inet0 --src 192.0.2.1 -j ACCEPT
-A OUTPUT -p esp -o inet0 --dst 192.0.2.1  -j ACCEPT

# IKE (udp 500)
# inet0 = device with public ip address, 192.0.2.1 = IP of the remote gateway
-A INPUT  -p udp -i inet0 --sport 500 --dport 500 --src 192.0.2.1  -j ACCEPT
-A OUTPUT -p udp -o inet0 --sport 500 --dport 500 --dst 192.0.2.1  -j ACCEPT

# NAT-Traversal
-A INPUT  -p udp -i inet0 --sport 4500 --dport 4500 --src 192.0.2.1  -j ACCEPT
-A OUTPUT -p udp -o inet0 --sport 4500 --dport 4500 --dst 192.0.2.1  -j ACCEPT
```

### Allow ICMP on all interfaces

To enable ICMP on all interfaces, add the following rules:

```
## Allow all ICMP messages
-A INPUT  -p icmp -j ACCEPT
-A OUTPUT -p icmp -j ACCEPT
-A FORWARD -p icmp -j ACCEPT
```

### Allow routing between two interfaces

The following example shows a symmetric allowed connection between two interfaces:

```
## allow routing between eth0 and eth1
-A FORWARD -i eth0 -o eth1 -j ACCEPT
-A FORWARD -o eth0 -i eth1 -j ACCEPT
```

Filtering can also be different in both directions and more specific concerning protocols and ports.

### Rejecting traffic with a specific ICMP message

You can reject traffic with ICMP messages meeting more closely the reason for the blocking. One example is the following:

```
-A INPUT -i eth1 -j REJECT --reject-with icmp-host-prohibited
```

In this example, traffic reaching the host over interface `eth1` from the outside is rejected with a `host prohibited` message.

### Mangle TCP packets to decrease packet size

When there are some problems with *Path MTU discovery*, you can mangle the TCP packets to decrease the *Maximum Segment Size*.

>**NOTE:** This method should though not be a permanent fix due to the limitations to TCP and the necessity to use PMTUD in conjunction with IPv6.

```
*mangle
# 1250 needs to be confirmed, 1387 was too much
-A POSTROUTING -p tcp --tcp-flags SYN,RST SYN -o inet0 -j TCPMSS --set-mss 1250
COMMIT
```

### BPF based Traffic Filtering

When there is a need for advanced Traffic Classification iptables, you can use `bpf` module.  

For this, the BPF assembly code must be compiled with `bpfc` to xt_bpf format.  

```bash
bpfc --input bpf-assembly.bpf -f xt_bpf
```  

To test the Functionality of the BPF assembly, use `netsniff-ng`. (The file must be in the pcap format)

```bash
bpfc -i test.bpf -f netsniff-ng | netsniff-ng -f - -i source.pcap -o dest.pcap -s
```

This bytecode can be used by `iptables` to act based on that.

```bash
iptables -I INPUT -m bpf -p udp --bytecode "52,48 0 0 9,...." -j CHAIN
```

## Examples

The following files will give you some examples of how to set up a useful configuration for `iptables`:

### IPsec with VTI (IPv4)

```
*filter

## Block all traffic silently as default policy
## Take care because this can cause harm if wrongly configured
-P INPUT DROP
-P FORWARD DROP
-P OUTPUT DROP

## Allows all loopback (lo) traffic and drop all traffic to 127/8 that doesn't use lo0
-A INPUT -i lo -j ACCEPT
-A INPUT ! -i lo -d 127.0.0.0/8 -j REJECT

## Allow all traffic from and to Calico network
-A INPUT -i eth0 -j ACCEPT
-A OUTPUT -o eth0 -j ACCEPT

# questionable if FWD for vxlan is needed

## allow incoming and outgoing traffic on vti interface
-A INPUT -i vti42 -j ACCEPT
-A OUTPUT -o vti42 -j ACCEPT
## allow routing on vti42 only if gre is not used
-A FORWARD -i vti42 -j ACCEPT
-A FORWARD -o vti42 -j ACCEPT

## allow icmp on inet0
-A INPUT -i inet0 -j ACCEPT -p icmp
-A OUTPUT -o inet0 -j ACCEPT -p icmp

## add rules for ipsec on external interface
# Only allow IPSEC traffic from and to the other side gateway
# ESP
-A INPUT  -p esp -i inet0 --src 192.0.2.1 -j ACCEPT
-A OUTPUT -p esp -o inet0 --dst 192.0.2.1  -j ACCEPT
# IKE (udp 500)
-A INPUT  -p udp -i inet0 --sport 500 --dport 500 --src 192.0.2.1  -j ACCEPT
-A OUTPUT -p udp -o inet0 --sport 500 --dport 500 --dst 192.0.2.1  -j ACCEPT
# NAT-Traversal
-A INPUT  -p udp -i inet0 --sport 4500 --dport 4500 --src 192.0.2.1  -j ACCEPT
-A OUTPUT -p udp -o inet0 --sport 4500 --dport 4500 --dst 192.0.2.1  -j ACCEPT

## Allow all ICMP messages
-A INPUT  -p icmp -j ACCEPT
-A OUTPUT -p icmp -j ACCEPT
-A FORWARD -p icmp -j ACCEPT

## reject forwarding on inet0 for debugging
#-A FORWARD -i inet0 -j REJECT --reject-with icmp-host-prohibited

## Block and reject traffic on net0 and net1 for debugging (if commented out will be dropped)
#-A INPUT -i net0 -j REJECT --reject-with icmp-host-prohibited
#-A INPUT -i net1 -j REJECT --reject-with icmp-host-prohibited
#-A OUTPUT -o net0 -j REJECT --reject-with icmp-host-prohibited
#-A OUTPUT -o net1 -j REJECT --reject-with icmp-host-prohibited

COMMIT

*mangle
# 1250 needs to be confirmed, 1387 was too much
-A POSTROUTING -p tcp --tcp-flags SYN,RST SYN -o inet0 -j TCPMSS --set-mss 1250
COMMIT
```

### IPsec with VTI (IPv6)

```
*filter

## Block all traffic silently as default policy
## Take care because this can cause harm if wrongly configured
-P INPUT DROP
-P FORWARD DROP
-P OUTPUT DROP

## Allows all loopback (lo) traffic and drop all traffic to 127/8 that doesn't use lo0
-A INPUT -i lo -j ACCEPT
-A INPUT ! -i lo -d ::1 -j REJECT

## Allow all traffic from and to Calico network
-A INPUT -i eth0 -j ACCEPT
-A OUTPUT -o eth0 -j ACCEPT

# questionable if FWD for vxlan is needed

## allow incoming and outgoing traffic on vti interface
#-A INPUT -i vti42 -j ACCEPT
#-A OUTPUT -o vti42 -j ACCEPT
## allow routing on vti42 only if gre is not used
#-A FORWARD -i vti42 -j ACCEPT
#-A FORWARD -o vti42 -j ACCEPT

## allow icmp on inet0
-A INPUT -i inet0 -j ACCEPT -p icmp
-A OUTPUT -o inet0 -j ACCEPT -p icmp

## Allow all ICMP messages
-A INPUT  -p icmp -j ACCEPT
-A OUTPUT -p icmp -j ACCEPT
-A FORWARD -p icmp -j ACCEPT

## reject forwarding on inet0 for debugging
#-A FORWARD -i inet0 -j REJECT --reject-with icmp-host-prohibited

## Block and reject traffic on net0 and net1 for debugging (if commented out will be dropped)
#-A INPUT -i net0 -j REJECT --reject-with icmp-host-prohibited
#-A INPUT -i net1 -j REJECT --reject-with icmp-host-prohibited
#-A OUTPUT -o net0 -j REJECT --reject-with icmp-host-prohibited
#-A OUTPUT -o net1 -j REJECT --reject-with icmp-host-prohibited

COMMIT

*mangle
# 1250 needs to be confirmed, 1387 was too much
-A POSTROUTING -p tcp --tcp-flags SYN,RST SYN -o inet0 -j TCPMSS --set-mss 1250
COMMIT
```

### IPsec with VTI and BGP routing

```
*filter

## Block all traffic silently as default policy
## Take care because this can cause harm if wrongly configured
#-P INPUT DROP
#-P FORWARD DROP
#-P OUTPUT DROP

## Allows all loopback (lo) traffic and drop all traffic to 127/8 that doesn't use lo0
-A INPUT -i lo -j ACCEPT
-A INPUT ! -i lo -d 127.0.0.0/8 -j REJECT

## Allow all traffic from and to Calico network
-A INPUT -i eth0 -j ACCEPT
-A OUTPUT -i eth0 -j ACCEPT

# questionable if FWD for vxlan is needed

## allow incoming and outgoing traffic on vti interface
-A INPUT -i vti42 -j ACCEPT
-A OUTPUT -i vti42 -j ACCEPT
## allow routing on vti42 only if gre is not used
# -A FORWARD -i vti42 ACCEPT
# -A FORWARD -o vti42 ACCEPT

## add rules for bgp interface
#-A INPUT -i gre1 -j ACCEPT -p tcp --dport 179
#-A OUTPUT -i gre1 -j ACCEPT -p tcp --dport 179

## reject forwarding on inet0 for debugging
-A FORWARD -i inet0 -j REJECT --reject-with icmp-host-prohibited

## allow icmp on inet0
-A INPUT -i inet0 -j ACCEPT -p icmp
-A OUTPUT -in inet0 -j ACCEPT -p icmp

## add rules for ipsec on external interface
# ESP
-A INPUT  -p esp -i inet0 -j ACCEPT
-A OUTPUT -p esp -o inet0 -s -j ACCEPT
# IKE (udp 500)
-A INPUT  -p udp -i inet0 --sport 500 --dport 500 -j ACCEPT
-A OUTPUT -p udp -o inet0 --sport 500 --dport 500 -j ACCEPT
# NAT-Traversal
-A INPUT  -p udp -i inet0 --sport 4500 --dport 4500 -j ACCEPT
-A OUTPUT -p udp -o inet0 --sport 4500 --dport 4500 -j ACCEPT

## via IPsec <--> Gateway: PING et. al.
# Allow all ICMP messages
-A INPUT  -p icmp -j ACCEPT
-A OUTPUT -p icmp -j ACCEPT

## via IPsec <--> sgi1
-A FORWARD -i gre1 -o sgi2 -p tcp -j ACCEPT
-A FORWARD -i gre2 -o sgi2 -p tcp -j ACCEPT
-A FORWARD -i sgo2 -o gre1 -p tcp -j ACCEPT
-A FORWARD -i sgo2 -o gre2 -p tcp -j ACCEPT

# Block and reject traffic on net0 and net1 for debugging (if commented out will be dropped)
-A INPUT -i net0 -j REJECT --reject-with icmp-host-prohibited
-A INPUT -i net1 -j REJECT --reject-with icmp-host-prohibited
-A OUTPUT -i net0 -j REJECT --reject-with icmp-host-prohibited
-A OUTPUT -i net1 -j REJECT --reject-with icmp-host-prohibited

# 1250 needs to be confirmed, 1387 was too much
-t mangle -A POSTROUTING -p tcp --tcp-flags SYN,RST SYN -o inet0 -j TCPMSS --set-mss 1250
-t mangle -A POSTROUTING -p tcp --tcp-flags SYN,RST SYN -o sgi2 -j TCPMSS --set-mss 1250
COMMIT
```

### UDP SYN flood detection inside GTPU

```
; IPv4 protocol: UDP
; ldh      [12]
ldb      [9]
jne      #0x11,bad

; Fragment offset == 0
; ldb      [23]
ldh      [6]
jset     #0x1fff,bad

; X <- offset_of_the_UDP_header - 14
; ldxb     4*([14]&0xf)
ldxb     4*([0]&0xf)

; check dest UDP port 2152
; ldh      [x + 16]
ldh      [x + 2]
jne      #2152,bad

; X <- start of the UDP datagram
; ld       #22
ld       #8
add      x
tax

; check GTPv1 message type T-PDU (0xff)
ldh      [x + 0]
and      #0xf0ff
jne      #0x30ff,bad

; skip past an extension header
skipext:
ldb      [x + 0]
jset     #0x04,ext,noext
ext:
ldb      [x + 12]
lsh      #2
add      x
add      #11
tax

; check if there are no more extensions
; FIXME: handle more extensions
ldb      [x + 0]
jne      #0,bad

ld       #1
jmp      innerip

; check for S or PN bits (E already checked)
; to get GTP-U header size
noext:
jset     #0x03,bighdr,smallhdr
bighdr:
ld       #12
jmp      innerip
smallhdr:
ld       #8

; move past the GTP-U header
innerip:
add      x
tax

; check inner IP version
ldb      [x + 0]
and      #0xf0
jne      #0x40,check_ipv6

; Fragment offset == 0
ldh      [x + 6]
jset     #0x1fff,bad

; Check for TCP (IPv4)
ldb      [x + 9]
jne      #0x06, bad

; skip past the IP header
ldb      [x + 0]
and      #0x0f
lsh      #2
jmp      check_syn

check_ipv6:
jne      #0x60,bad

; check for TCP (IPv6)
ldb      [x + 6]
jne      #0x06, bad

ld       #40

; check TCP flags (should have only SYN bit set)
check_syn:
add      x
tax
ldh      [x + 12]
jset     #0x0002,syn_set,bad
syn_set:
jset     #0x0ffd,bad

good:
ret #65535

bad:
ret #0
```
