goiptrieebpf

How to create slice of LPM trie record for IPs/CIDRs


I am trying to use the BatchUpdate and BatchDelete API from https://github.com/cilium/ebpf/blob/master/map.go#L952-L1038. from my understanding, I need to create slice of LPM trie of IPs/CIRDs, for example: if I have denyIPs := []string{"10.11.15.114/32", "127.0.0.1/32"}, I need to convert the denyIPs to slice of LPM trie, I google searched and unable to find example I can learn (still newbie to Golang). my intention is to replace my https://github.com/vincentmli/xdp-firewall/blob/main/main.go#L78-L102 with batch update and delete.


Solution

  • You are supplying Go strings in unparsed format. The key of an LPM trie must always follow

    struct bpf_lpm_trie_key {
        __u32   prefixlen;  /* up to 32 for AF_INET, 128 for AF_INET6 */
        __u8    data[0];    /* Arbitrary size */
    };
    

    So the first 4 bytes must contain your prefix as a 32-bit unsigned integer. Followed by in your case the 4 bytes of your IPv4 address. So you will have to do some parsing of your strings.

    The eBPF library can marshal structs, so the easiest way to go is to define a struct for your key:

    type MapKey struct {
      Prefix  uint32
      Address [4]byte
    }
    

    Then provide a slice of these map keys []MapKey to the batch functions.