├── docker └── builder │ └── Dockerfile ├── Makefile ├── src ├── Makefile ├── common.h ├── test │ └── test_xdp_dns.py ├── xdp_dns.c └── xdp_dns_kern.c ├── README.md └── LICENSE /docker/builder/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM debian:bullseye 2 | RUN apt-get update && apt-get install -y make clang-11 llvm-11 libc6-dev libc6-dev-i386 libz-dev libelf-dev libbpf-dev iproute2 && apt-get clean 3 | RUN ln -s $(which clang-11) /usr/bin/clang && ln -s $(which llc-11) /usr/bin/llc 4 | #For testing 5 | # RUN apt-get update && apt-get install -y python3 python3-scapy python3-bpfcc linux-headers-$(uname -r) 6 | #For debugging 7 | # RUN DEBIAN_FRONTEND=noninteractive apt install -y strace bpftool lldb scapy tmux dnsutils tcpdump tshark termshark nano 8 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | # Makefile for building xdp_dns in a Docker container 2 | 3 | #DEBUG = y enables printk in the BPF program 4 | DEBUG ?= n 5 | #Compiler flags for specific DNS features 6 | EDNS ?= y #RFC6891 7 | 8 | all: builder xdp_dns 9 | 10 | builder: 11 | docker build -t bpf-builder:latest docker/builder 12 | 13 | xdp_dns: builder 14 | docker run --rm -ti -v$(shell pwd):/input -v$(shell pwd)/build:/output \ 15 | bpf-builder sh -c "cd /input/src && make DEBUG=$(DEBUG) FEATURE_EDNS=$(EDNS)" 16 | 17 | test: builder 18 | docker run --privileged --rm -ti -v$(shell pwd):/input -v$(shell pwd)/build:/output \ 19 | bpf-builder sh -c "cd /input/src && python3 test/test_xdp_dns.py" 20 | 21 | clean: 22 | docker rmi bpf-builder 23 | make -C ./src clean 24 | -------------------------------------------------------------------------------- /src/Makefile: -------------------------------------------------------------------------------- 1 | # SPDX-License-Identifier: GPL-2.0-or-later 2 | # -------------------------------------------------- 3 | # Makefile for xdp_dns 4 | # -------------------------------------------------- 5 | CLANG = clang 6 | LLC = llc 7 | #DEBUG = y enables printk in the BPF program 8 | DEBUG ?= n 9 | 10 | #Specific DNS features that can be enabled/disabled 11 | FEATURE_EDNS ?= y 12 | 13 | #Path to include files of respectively libbpf-dev and iproute2 14 | LIBBPF_INCLUDE ?= /usr/include/bpf 15 | IPROUTE_INCLUDE ?= /usr/include/iproute2 16 | 17 | SRC_DIR=. 18 | #vpath %.c $(SRC_DIR) 19 | #vpath %.h $(SRC_DIR) 20 | 21 | LIBBPF_DIR ?= /usr/lib/$(shell uname -m)-linux-gnu 22 | #Requires libbpf-dev package 23 | OBJECT_LIBBPF = libbpf.a 24 | 25 | CFLAGS ?= -I$(LIBBPF_INCLUDE) -I $(IPROUTE_INCLUDE) -g -static 26 | LDFLAGS ?= -L$(LIBBPF_DIR) 27 | LDLIBS ?= -l:libbpf.a -lelf -lz 28 | 29 | BPF_CFLAGS ?= -I $(LIBBPF_INCLUDE) \ 30 | -I $(IPROUTE_INCLUDE) 31 | 32 | ifeq ($(DEBUG),y) 33 | BPF_EXTRA_FLAGS += -D DEBUG 34 | endif 35 | 36 | ifeq ($(FEATURE_EDNS),y) 37 | BPF_EXTRA_FLAGS += -D EDNS 38 | endif 39 | 40 | all: llvm-check xdp_dns_kern xdp_dns 41 | 42 | .PHONY: clean $(CLANG) $(LLC) 43 | 44 | clean: 45 | rm -f *.o 46 | rm -f *.ll 47 | rm -f *~ 48 | 49 | llvm-check: $(CLANG) $(LLC) 50 | @for TOOL in $^ ; do \ 51 | if [ ! $$(command -v $${TOOL} 2>/dev/null) ]; then \ 52 | echo "*** ERROR: Cannot find tool $${TOOL}" ;\ 53 | exit 1; \ 54 | else true; fi; \ 55 | done 56 | 57 | xdp_dns: %: %.c Makefile 58 | $(CLANG) \ 59 | -Wall \ 60 | $(CFLAGS) \ 61 | $(LDFLAGS) \ 62 | -o xdns \ 63 | $< $(LDLIBS) 64 | 65 | xdp_dns_kern: %: %.c Makefile 66 | $(CLANG) \ 67 | -target bpf \ 68 | $(BPF_CFLAGS) \ 69 | -Wall $(BPF_EXTRA_FLAGS) \ 70 | -O2 -c -o $@.o $< 71 | -------------------------------------------------------------------------------- /src/common.h: -------------------------------------------------------------------------------- 1 | /* SPDX-License-Identifier: GPL-2.0-or-later */ 2 | #ifndef BCC_SEC 3 | #include 4 | #endif 5 | 6 | #define A_RECORD_TYPE 0x0001 7 | #define DNS_CLASS_IN 0x0001 8 | //RFC1034: the total number of octets that represent a domain name is limited to 255. 9 | //We need to be aligned so the struct does not include padding bytes. We'll set the length to 256. 10 | //Otherwise padding bytes will generate problems with the verifier, as it ?could contain arbitrary data from memory? 11 | #define MAX_DNS_NAME_LENGTH 256 12 | 13 | struct dns_hdr 14 | { 15 | uint16_t transaction_id; 16 | uint8_t rd : 1; //Recursion desired 17 | uint8_t tc : 1; //Truncated 18 | uint8_t aa : 1; //Authoritive answer 19 | uint8_t opcode : 4; //Opcode 20 | uint8_t qr : 1; //Query/response flag 21 | uint8_t rcode : 4; //Response code 22 | uint8_t cd : 1; //Checking disabled 23 | uint8_t ad : 1; //Authenticated data 24 | uint8_t z : 1; //Z reserved bit 25 | uint8_t ra : 1; //Recursion available 26 | uint16_t q_count; //Number of questions 27 | uint16_t ans_count; //Number of answer RRs 28 | uint16_t auth_count; //Number of authority RRs 29 | uint16_t add_count; //Number of resource RRs 30 | }; 31 | 32 | #ifdef EDNS 33 | struct ar_hdr { 34 | uint8_t name; 35 | uint16_t type; 36 | uint16_t size; 37 | uint32_t ex_rcode; 38 | uint16_t rcode_len; 39 | } __attribute__((packed)); 40 | #endif 41 | 42 | //Used as key in our hashmap 43 | struct dns_query { 44 | uint16_t record_type; 45 | uint16_t class; 46 | char name[MAX_DNS_NAME_LENGTH]; 47 | }; 48 | 49 | //Used as a generic DNS response 50 | struct dns_response { 51 | uint16_t query_pointer; 52 | uint16_t record_type; 53 | uint16_t class; 54 | uint32_t ttl; 55 | uint16_t data_length; 56 | } __attribute__((packed)); 57 | 58 | //Used as value of our A record hashmap 59 | struct a_record { 60 | struct in_addr ip_addr; 61 | uint32_t ttl; 62 | }; 63 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Xpress DNS - Experimental XDP DNS server 2 | 3 | ## About 4 | Xpress DNS is an experimental DNS server written in BPF for high throughput, low latency DNS responses. 5 | It uses [eXpress Data Path](https://en.wikipedia.org/wiki/Express_Data_Path) to process packets early in the Linux networking path. 6 | A user space application is provided to add DNS records to a BPF map which is read from in-kernel by the XDP module. 7 | DNS requests that do not match are passed on to the Linux networking stack. 8 | 9 | ## Use case 10 | Xpress DNS could be used as a high performance DNS proxy for common DNS requests of static DNS records. 11 | By responding to DNS requests before the packet gets processed by the Linux networking stack, it alleviates load on the system and DNS servers in user space. 12 | 13 | ## Features & limitations 14 | * Currently supports A records 15 | * Only supports plain DNS over UDP (port 53) 16 | * Basic EDNS implementation 17 | * Only responds to single queries for now 18 | * No recursive lookups 19 | 20 | ## Requirements 21 | * Kernel version 5.8 or higher is required as this program uses the `bpf_xdp_adjust_tail` call to extend packet size. See https://lwn.net/Articles/820562/, merged in 5.8. 22 | * iproute2 to load the BPF object on a network device 23 | 24 | ## How to build 25 | To build this software we use Docker to ensure a reproducable build environment. 26 | With Docker installed, run the `make` command in the root of the repository. 27 | 28 | To build the software without Docker: install llvm, clang, libbpf-dev, iproute2 and run the `make` command in the `src` directory. 29 | 30 | ## How to use 31 | Load the `xdp_dns_kern.o` BPF object using iproute2 on the target network interface (veth0 in the example below): 32 | ```bash 33 | ip link set dev veth0 xdp obj ./src/xdp_dns_kern.o 34 | ``` 35 | 36 | Use the `xdns` user space application to manage DNS records. 37 | ```bash 38 | Usage: xdns add record_type domain_name value [ttl] 39 | xdns remove record_type domain_name value 40 | xdns list 41 | ``` 42 | Example: ```xdns add a foo.bar 127.0.0.1 120``` 43 | 44 | Use `xdns list` to list all configured DNS records. 45 | 46 | ## How to test & debug 47 | Xpress DNS is compatible with BCC toolkit and can be instrumented with its Python bindings. 48 | You can refer to the supplied unit tests in [test_xdp_dns.py](src/test/test_xdp_dns.py) for pointers on how to test the code using BCC, scapy and Python's unit test module. 49 | Run `make test` in the root directory to run the supplied unit tests. 50 | 51 | Build with `make DEBUG=y` to enable debug logging, which logs debug information to `/sys/kernel/debug/tracing/trace_pipe` 52 | 53 | ## License 54 | This repository is licensed under GPLv2.0. 55 | See LICENSE file for details. 56 | -------------------------------------------------------------------------------- /src/test/test_xdp_dns.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import codecs 3 | from bcc import BPF, libbcc 4 | import ctypes 5 | from scapy.all import * 6 | 7 | #Struct representing the dns_query struct in common.h 8 | class DNS_QUERY(ctypes.Structure): 9 | _fields_ = [("record_type", ctypes.c_uint16), 10 | ("class", ctypes.c_uint16), 11 | ("name", ctypes.c_char * 512)] 12 | 13 | #Struct representing the a_record struct in common.h 14 | class A_RECORD(ctypes.Structure): 15 | _fields_ = [("ip_addr", ctypes.c_uint32), 16 | ("ttl", ctypes.c_uint32)] 17 | 18 | 19 | class DnsTestCase(unittest.TestCase): 20 | bpf = None 21 | func = None 22 | 23 | SKB_OUT_SIZE = 1514 #MTU 1500 + 14 eth size 24 | 25 | def _xdp_test_run(self, given_packet, expected_packet, expected_return, repeat=1): 26 | size = len(given_packet) 27 | given_packet = ctypes.create_string_buffer(raw(given_packet), size) 28 | packet_output = ctypes.create_string_buffer(self.SKB_OUT_SIZE) 29 | packet_output_size = ctypes.c_uint32() 30 | retval = ctypes.c_uint32() 31 | duration = ctypes.c_uint32() 32 | ret = libbcc.lib.bpf_prog_test_run(self.func.fd, 33 | repeat, 34 | ctypes.byref(given_packet), 35 | size, 36 | ctypes.byref(packet_output), 37 | ctypes.byref(packet_output_size), 38 | ctypes.byref(retval), 39 | ctypes.byref(duration)) 40 | self.assertEqual(ret, 0) 41 | self.assertEqual(retval.value, expected_return) 42 | 43 | if expected_packet: 44 | self.assertEqual(packet_output[:packet_output_size.value], raw(expected_packet)) 45 | 46 | def setUp(self): 47 | self.bpf = BPF(src_file=b"xdp_dns_kern.c") 48 | self.func = self.bpf.load_func(b"xdp_dns", BPF.XDP) 49 | 50 | def test_dns_no_match(self): 51 | packet_in = Ether() / IP() / UDP() / DNS(rd=1, qd=DNSQR(qname="foo.bar")) 52 | self._xdp_test_run(packet_in, packet_in, BPF.XDP_PASS) 53 | 54 | def test_dns_match(self): 55 | packet_in = (Ether(dst="aa:bb:cc:dd:ee:ff", src="ff:aa:ff:aa:ff:aa") / 56 | IP() / 57 | UDP(sport=50000, dport=53) / 58 | DNS(rd=1, qd=DNSQR(qname="foo.bar"))) 59 | 60 | #chksum 5213 61 | packet_out = (Ether(dst="ff:aa:ff:aa:ff:aa", src="aa:bb:cc:dd:ee:ff")/ 62 | IP()/ 63 | UDP(sport=53, dport=50000, chksum=0)/ 64 | DNS(qr=1, rd=1, ra=1, ancount=1, 65 | qd=DNSQR(qname="foo.bar"), 66 | an=DNSRR(rrname=codecs.decode("c00c", 'hex'), type="A", rclass="IN", ttl=120, rdlen=4, rdata="1.2.3.4"))) 67 | 68 | name = "\3" + "foo" + "\3" + "bar" + ("\0" * 504) 69 | q = DNS_QUERY(ctypes.c_uint16(1), ctypes.c_uint16(1), str.encode(name)) 70 | a = A_RECORD(ctypes.c_uint32(67305985), ctypes.c_uint32(120)) 71 | 72 | self.bpf["xdns_a_records"][q] = a 73 | self._xdp_test_run(packet_in, packet_out, BPF.XDP_TX) 74 | 75 | if __name__ == '__main__': 76 | unittest.main() 77 | -------------------------------------------------------------------------------- /src/xdp_dns.c: -------------------------------------------------------------------------------- 1 | /* 2 | Xpress DNS: Experimental XDP DNS responder 3 | Copyright (C) 2021 Bas Schalbroeck 4 | 5 | SPDX-License-Identifier: GPL-2.0-or-later 6 | 7 | This program is free software; you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation; either version 2, or (at your option) 10 | any later version. 11 | 12 | This program is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with this program; if not, write to the Free Software 19 | Foundation, Inc., 59 Temple Place - Suite 330 20 | */ 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | //bpf_elf.h is part of iproute2 28 | #include 29 | #include "common.h" 30 | 31 | int get_map_fd(const char *map_path); 32 | void replace_dots_with_length_octets(char *dns_name, char *new_dns_name); 33 | void replace_length_octets_with_dots(char *dns_name, char *new_dns_name); 34 | 35 | static const char *a_records_map_path = "/sys/fs/bpf/xdp/globals/xdns_a_records"; 36 | 37 | void usage(char *progname) 38 | { 39 | fprintf(stderr, "Usage: %s add record_type domain_name value [ttl]\n", progname); 40 | fprintf(stderr, " %s remove record_type domain_name value\n", progname); 41 | fprintf(stderr, " %s list\n", progname); 42 | fprintf(stderr, "\nExamples:\n"); 43 | fprintf(stderr, " %s add a foo.bar 1.2.3.4 120\n", progname); 44 | } 45 | 46 | int main(int argc, char **argv) 47 | { 48 | //Return code 49 | int ret = EINVAL; 50 | 51 | //Initialize file descriptor for a_records map 52 | int a_records_fd; 53 | a_records_fd = get_map_fd(a_records_map_path); 54 | if (a_records_fd < 0) 55 | return EXIT_FAILURE; 56 | 57 | if (argc == 2) 58 | { 59 | if (strcmp(argv[1], "list") == 0) 60 | { 61 | struct dns_query key, next_key; 62 | struct a_record value; 63 | int res = -1; 64 | while (bpf_map_get_next_key(a_records_fd, &key, &next_key) == 0) 65 | { 66 | res = bpf_map_lookup_elem(a_records_fd, &next_key, &value); 67 | if (res > -1) 68 | { 69 | char new_dns_name[strnlen(next_key.name, MAX_DNS_NAME_LENGTH)]; 70 | replace_length_octets_with_dots(next_key.name, new_dns_name); 71 | printf("A %s %s %i\n", new_dns_name, inet_ntoa(value.ip_addr), value.ttl); 72 | } 73 | key = next_key; 74 | } 75 | ret = 0; 76 | } 77 | } 78 | else if (argc == 5 || argc == 6) 79 | { 80 | if (strcmp(argv[1], "add") == 0 || strcmp(argv[1], "remove") == 0) 81 | { 82 | struct in_addr ip_addr; 83 | 84 | //Check for 'A' record 85 | if (strcmp(argv[2], "a") == 0 || strcmp(argv[2], "A") == 0) 86 | { 87 | if (inet_aton(argv[4], &ip_addr) == 0) 88 | { 89 | printf("ERROR: Invalid IP address\n"); 90 | ret = EINVAL; 91 | return ret; 92 | } 93 | 94 | } else { 95 | printf("ERROR: %s is not a DNS record type.\n", argv[2]); 96 | ret = EINVAL; 97 | return ret; 98 | } 99 | 100 | //Create a new dns_name char array 101 | char new_dns_name[MAX_DNS_NAME_LENGTH]; 102 | //Zero fill the new_dns_name 103 | memset(&new_dns_name, 0, sizeof(new_dns_name)); 104 | replace_dots_with_length_octets(argv[3], new_dns_name); 105 | 106 | struct dns_query dns; 107 | dns.class = DNS_CLASS_IN; 108 | dns.record_type = A_RECORD_TYPE; 109 | memcpy(dns.name, new_dns_name, sizeof(new_dns_name)); 110 | 111 | if (strcmp(argv[1], "add") == 0) 112 | { 113 | struct a_record a; 114 | a.ip_addr = ip_addr; 115 | if(argc == 5){ 116 | a.ttl = 0; 117 | } else { 118 | a.ttl = (uint32_t)atoi(argv[5]); 119 | } 120 | bpf_map_update_elem(a_records_fd, &dns, &a, BPF_ANY); 121 | printf("DNS record added\n"); 122 | ret = 0; 123 | } 124 | else if (strcmp(argv[1], "remove") == 0) 125 | { 126 | if (bpf_map_delete_elem(a_records_fd, &dns) == 0) 127 | { 128 | printf("DNS record removed\n"); 129 | ret = 0; 130 | } 131 | else 132 | { 133 | printf("DNS record not found\n"); 134 | ret = ENOENT; 135 | } 136 | } 137 | } 138 | } 139 | 140 | if(ret != 0) 141 | usage(argv[0]); 142 | 143 | return ret; 144 | } 145 | 146 | //Calculate and insert length octets between DNS name labels. RFC1035 4.1.2 147 | void replace_dots_with_length_octets(char *dns_name, char *new_dns_name) 148 | { 149 | uint16_t name_len = strnlen(dns_name, 255); 150 | int i; 151 | int cnt = 0; 152 | 153 | for (i = 0; i <= name_len; i++) 154 | { 155 | //If dot character or end of string is detected 156 | if (dns_name[i] == 46 || dns_name[i] == 0) 157 | { 158 | //Put length octet with value [cnt] at location [i-cnt] 159 | new_dns_name[i - cnt] = cnt; 160 | 161 | //Break loop if zero 162 | if (dns_name[i] == 0) 163 | { 164 | cnt = i + 1; 165 | break; 166 | } 167 | 168 | //Reset counter 169 | cnt = -1; 170 | } 171 | 172 | new_dns_name[i + 1] = dns_name[i]; 173 | 174 | //Count number of characters until the dot character 175 | cnt++; 176 | } 177 | 178 | new_dns_name[cnt] = 0; 179 | } 180 | 181 | void replace_length_octets_with_dots(char *dns_name, char *new_dns_name) 182 | { 183 | uint16_t name_len = strnlen(dns_name, 255); 184 | 185 | //Retrieve first label length octet 186 | char label_length = dns_name[0]; 187 | int i; 188 | //Loop through dns name, starting at 1 (as position 0 contains length octet) 189 | for (i = 1; i <= name_len; i++) 190 | { 191 | //Break loop if zero 192 | if (dns_name[i] == 0) 193 | { 194 | new_dns_name[i - 1] = 0; 195 | break; 196 | } 197 | else if (label_length == 0) 198 | { 199 | new_dns_name[i - 1] = '.'; 200 | //Set label_length to current label length octet 201 | label_length = dns_name[i]; 202 | } 203 | else 204 | { 205 | new_dns_name[i - 1] = dns_name[i]; 206 | label_length--; 207 | } 208 | } 209 | } 210 | 211 | int get_map_fd(const char *map_path) 212 | { 213 | int fd = bpf_obj_get(map_path); 214 | if (fd < 0) 215 | { 216 | if (errno == EACCES) 217 | { 218 | printf("ERROR: Permission denied while trying to access %s\n", map_path); 219 | } 220 | else if (errno == ENOENT) 221 | { 222 | printf("ERROR: Could not find BPF maps. Load XDP program with iproute2 first.\n"); 223 | } 224 | else 225 | { 226 | printf("ERROR: BPF map error: %d (%s)\n", errno, strerror(errno)); 227 | } 228 | } 229 | return fd; 230 | } 231 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | 294 | Copyright (C) 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | , 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. -------------------------------------------------------------------------------- /src/xdp_dns_kern.c: -------------------------------------------------------------------------------- 1 | /* 2 | Xpress DNS: Experimental XDP DNS responder 3 | Copyright (C) 2021 Bas Schalbroeck 4 | 5 | SPDX-License-Identifier: GPL-2.0-or-later 6 | 7 | This program is free software; you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation; either version 2, or (at your option) 10 | any later version. 11 | 12 | This program is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with this program; if not, write to the Free Software 19 | Foundation, Inc., 59 Temple Place - Suite 330 20 | */ 21 | #define DEFAULT_ACTION XDP_PASS 22 | 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include 28 | 29 | //This program supports XDP in BCC and libbpf+iproute2 mode 30 | //Include different files depending on mode 31 | #ifndef BCC_SEC 32 | #include 33 | #include 34 | #include 35 | #include 36 | #include 37 | //bpf_elf.h is part of iproute2 38 | #include 39 | #endif 40 | 41 | #include "common.h" 42 | 43 | //Create different BPF maps depending on if we're using libbpf or BCC 44 | #ifdef BCC_SEC 45 | BPF_HASH(xdns_a_records, struct dns_query, struct a_record); 46 | #else 47 | //Hash table for DNS A Records loaded by iproute2 48 | //Key is a dns_query struct, value is the associated IPv4 address 49 | struct bpf_elf_map SEC("maps") xdns_a_records = { 50 | .type = BPF_MAP_TYPE_HASH, 51 | .size_key = sizeof(struct dns_query), 52 | .size_value = sizeof(struct a_record), 53 | .max_elem = 65536, 54 | .pinning = 2, //PIN_GLOBAL_NS 55 | }; 56 | #endif 57 | 58 | static int match_a_records(struct xdp_md *ctx, struct dns_query *q, struct a_record *a); 59 | static int parse_query(struct xdp_md *ctx, void *query_start, struct dns_query *q); 60 | static void create_query_response(struct a_record *a, char *dns_buffer, size_t *buf_size); 61 | #ifdef EDNS 62 | static inline int create_ar_response(struct ar_hdr *ar, char *dns_buffer, size_t *buf_size); 63 | static inline int parse_ar(struct xdp_md *ctx, struct dns_hdr *dns_hdr, int query_length, struct ar_hdr *ar); 64 | #endif 65 | static inline void modify_dns_header_response(struct dns_hdr *dns_hdr); 66 | static inline void update_ip_checksum(void *data, int len, uint16_t *checksum_location); 67 | static inline void copy_to_pkt_buf(struct xdp_md *ctx, void *dst, void *src, size_t n); 68 | static inline void swap_mac(uint8_t *src_mac, uint8_t *dst_mac); 69 | 70 | char dns_buffer[512]; 71 | 72 | #ifndef BCC_SEC 73 | SEC("prog") 74 | #endif 75 | int xdp_dns(struct xdp_md *ctx) 76 | { 77 | #ifdef DEBUG 78 | uint64_t start = bpf_ktime_get_ns(); 79 | #endif 80 | #ifdef BCC_SEC 81 | char dns_buffer[512]; 82 | #endif 83 | 84 | void *data_end = (void *)(unsigned long)ctx->data_end; 85 | void *data = (void *)(unsigned long)ctx->data; 86 | 87 | //Boundary check: check if packet is larger than a full ethernet + ip header 88 | if (data + sizeof(struct ethhdr) + sizeof(struct iphdr) > data_end) 89 | { 90 | return DEFAULT_ACTION; 91 | } 92 | 93 | struct ethhdr *eth = data; 94 | 95 | //Ignore packet if ethernet protocol is not IP-based 96 | if (eth->h_proto != bpf_htons(ETH_P_IP)) 97 | { 98 | return DEFAULT_ACTION; 99 | } 100 | 101 | struct iphdr *ip = data + sizeof(*eth); 102 | 103 | if (ip->protocol == IPPROTO_UDP) 104 | { 105 | struct udphdr *udp; 106 | //Boundary check for UDP 107 | if (data + sizeof(*eth) + sizeof(*ip) + sizeof(*udp) > data_end) 108 | { 109 | return DEFAULT_ACTION; 110 | } 111 | 112 | udp = data + sizeof(*eth) + sizeof(*ip); 113 | 114 | //Check if dest port equals 53 115 | if (udp->dest == bpf_htons(53)) 116 | { 117 | #ifdef DEBUG 118 | bpf_printk("Packet dest port 53"); 119 | bpf_printk("Data pointer starts at %u", data); 120 | #endif 121 | 122 | //Boundary check for minimal DNS header 123 | if (data + sizeof(*eth) + sizeof(*ip) + sizeof(*udp) + sizeof(struct dns_hdr) > data_end) 124 | { 125 | return DEFAULT_ACTION; 126 | } 127 | 128 | struct dns_hdr *dns_hdr = data + sizeof(*eth) + sizeof(*ip) + sizeof(*udp); 129 | 130 | //Check if header contains a standard query 131 | if (dns_hdr->qr == 0 && dns_hdr->opcode == 0) 132 | { 133 | #ifdef DEBUG 134 | bpf_printk("DNS query transaction id %u", bpf_ntohs(dns_hdr->transaction_id)); 135 | #endif 136 | 137 | //Get a pointer to the start of the DNS query 138 | void *query_start = (void *)dns_hdr + sizeof(struct dns_hdr); 139 | 140 | //We will only be parsing a single query for now 141 | struct dns_query q; 142 | int query_length = 0; 143 | query_length = parse_query(ctx, query_start, &q); 144 | if (query_length < 1) 145 | { 146 | return DEFAULT_ACTION; 147 | } 148 | 149 | //Check if query matches a record in our hash table 150 | struct a_record a_record; 151 | int res = match_a_records(ctx, &q, &a_record); 152 | 153 | //If query matches... 154 | if (res == 0) 155 | { 156 | size_t buf_size = 0; 157 | 158 | //Change DNS header to a valid response header 159 | modify_dns_header_response(dns_hdr); 160 | 161 | //Create DNS response and add to temporary buffer. 162 | create_query_response(&a_record, &dns_buffer[buf_size], &buf_size); 163 | 164 | #ifdef EDNS 165 | //If an additional record is present 166 | if(dns_hdr->add_count > 0) 167 | { 168 | //Parse AR record 169 | struct ar_hdr ar; 170 | if(parse_ar(ctx, dns_hdr, query_length, &ar) != -1) 171 | { 172 | //Create AR response and add to temporary buffer 173 | create_ar_response(&ar, &dns_buffer[buf_size], &buf_size); 174 | } 175 | } 176 | #endif 177 | 178 | //Start our response [query_length] bytes beyond the header 179 | void *answer_start = (void *)dns_hdr + sizeof(struct dns_hdr) + query_length; 180 | //Determine increment of packet buffer 181 | int tailadjust = answer_start + buf_size - data_end; 182 | 183 | //Adjust packet length accordingly 184 | if (bpf_xdp_adjust_tail(ctx, tailadjust)) 185 | { 186 | #ifdef DEBUG 187 | bpf_printk("Adjust tail fail"); 188 | #endif 189 | } 190 | else 191 | { 192 | //Because we adjusted packet length, mem addresses might be changed. 193 | //Reinit pointers, as verifier will complain otherwise. 194 | data = (void *)(unsigned long)ctx->data; 195 | data_end = (void *)(unsigned long)ctx->data_end; 196 | 197 | //Copy bytes from our temporary buffer to packet buffer 198 | copy_to_pkt_buf(ctx, data + sizeof(struct ethhdr) + 199 | sizeof(struct iphdr) + 200 | sizeof(struct udphdr) + 201 | sizeof(struct dns_hdr) + 202 | query_length, 203 | &dns_buffer[0], buf_size); 204 | 205 | eth = data; 206 | ip = data + sizeof(struct ethhdr); 207 | udp = data + sizeof(struct ethhdr) + sizeof(struct iphdr); 208 | 209 | //Do a new boundary check 210 | if (data + sizeof(struct ethhdr) + sizeof(struct iphdr) + sizeof(struct udphdr) > data_end) 211 | { 212 | #ifdef DEBUG 213 | bpf_printk("Error: Boundary exceeded"); 214 | #endif 215 | return DEFAULT_ACTION; 216 | } 217 | 218 | //Adjust UDP length and IP length 219 | uint16_t iplen = (data_end - data) - sizeof(struct ethhdr); 220 | uint16_t udplen = (data_end - data) - sizeof(struct ethhdr) - sizeof(struct iphdr); 221 | ip->tot_len = bpf_htons(iplen); 222 | udp->len = bpf_htons(udplen); 223 | 224 | //Swap eth macs 225 | swap_mac((uint8_t *)eth->h_source, (uint8_t *)eth->h_dest); 226 | 227 | //Swap src/dst IP 228 | uint32_t src_ip = ip->saddr; 229 | ip->saddr = ip->daddr; 230 | ip->daddr = src_ip; 231 | 232 | //Set UDP checksum to zero 233 | udp->check = 0; 234 | 235 | //Swap udp src/dst ports 236 | uint16_t tmp_src = udp->source; 237 | udp->source = udp->dest; 238 | udp->dest = tmp_src; 239 | 240 | //Recalculate IP checksum 241 | update_ip_checksum(ip, sizeof(struct iphdr), &ip->check); 242 | 243 | #ifdef DEBUG 244 | bpf_printk("XDP_TX"); 245 | #endif 246 | 247 | 248 | #ifdef DEBUG 249 | uint64_t end = bpf_ktime_get_ns(); 250 | uint64_t elapsed = end-start; 251 | bpf_printk("Time elapsed: %d", elapsed); 252 | #endif 253 | 254 | //Emit modified packet 255 | return XDP_TX; 256 | } 257 | } 258 | } 259 | } 260 | } 261 | 262 | return DEFAULT_ACTION; 263 | } 264 | 265 | static int match_a_records(struct xdp_md *ctx, struct dns_query *q, struct a_record *a) 266 | { 267 | #ifdef DEBUG 268 | bpf_printk("DNS record type: %i", q->record_type); 269 | bpf_printk("DNS class: %i", q->class); 270 | bpf_printk("DNS name: %s", q->name); 271 | #endif 272 | 273 | struct a_record *record; 274 | #ifdef BCC_SEC 275 | record = xdns_a_records.lookup(q); 276 | #else 277 | record = bpf_map_lookup_elem(&xdns_a_records, q); 278 | #endif 279 | 280 | //If record pointer is not zero.. 281 | if (record > 0) 282 | { 283 | #ifdef DEBUG 284 | bpf_printk("DNS query matched"); 285 | #endif 286 | a->ip_addr = record->ip_addr; 287 | a->ttl = record->ttl; 288 | 289 | return 0; 290 | } 291 | 292 | return -1; 293 | } 294 | 295 | //Parse query and return query length 296 | static int parse_query(struct xdp_md *ctx, void *query_start, struct dns_query *q) 297 | { 298 | void *data_end = (void *)(long)ctx->data_end; 299 | 300 | #ifdef DEBUG 301 | bpf_printk("Parsing query"); 302 | #endif 303 | 304 | uint16_t i; 305 | void *cursor = query_start; 306 | int namepos = 0; 307 | 308 | //Fill dns_query.name with zero bytes 309 | //Not doing so will make the verifier complain when dns_query is used as a key in bpf_map_lookup 310 | memset(&q->name[0], 0, sizeof(q->name)); 311 | //Fill record_type and class with default values to satisfy verifier 312 | q->record_type = 0; 313 | q->class = 0; 314 | 315 | //We create a bounded loop of MAX_DNS_NAME_LENGTH (maximum allowed dns name size). 316 | //We'll loop through the packet byte by byte until we reach '0' in order to get the dns query name 317 | for (i = 0; i < MAX_DNS_NAME_LENGTH; i++) 318 | { 319 | 320 | //Boundary check of cursor. Verifier requires a +1 here. 321 | //Probably because we are advancing the pointer at the end of the loop 322 | if (cursor + 1 > data_end) 323 | { 324 | #ifdef DEBUG 325 | bpf_printk("Error: boundary exceeded while parsing DNS query name"); 326 | #endif 327 | break; 328 | } 329 | 330 | /* 331 | #ifdef DEBUG 332 | bpf_printk("Cursor contents is %u\n", *(char *)cursor); 333 | #endif 334 | */ 335 | 336 | //If separator is zero we've reached the end of the domain query 337 | if (*(char *)(cursor) == 0) 338 | { 339 | 340 | //We've reached the end of the query name. 341 | //This will be followed by 2x 2 bytes: the dns type and dns class. 342 | if (cursor + 5 > data_end) 343 | { 344 | #ifdef DEBUG 345 | bpf_printk("Error: boundary exceeded while retrieving DNS record type and class"); 346 | #endif 347 | } 348 | else 349 | { 350 | q->record_type = bpf_htons(*(uint16_t *)(cursor + 1)); 351 | q->class = bpf_htons(*(uint16_t *)(cursor + 3)); 352 | } 353 | 354 | //Return the bytecount of (namepos + current '0' byte + dns type + dns class) as the query length. 355 | return namepos + 1 + 2 + 2; 356 | } 357 | 358 | //Read and fill data into struct 359 | q->name[namepos] = *(char *)(cursor); 360 | namepos++; 361 | cursor++; 362 | } 363 | 364 | return -1; 365 | } 366 | 367 | 368 | #ifdef EDNS 369 | //Parse additonal record 370 | static inline int parse_ar(struct xdp_md *ctx, struct dns_hdr *dns_hdr, int query_length, struct ar_hdr *ar) 371 | { 372 | #ifdef DEBUG 373 | bpf_printk("Parsing additional record in query"); 374 | #endif 375 | 376 | void *data_end = (void *)(long)ctx->data_end; 377 | 378 | //Parse ar record 379 | ar = (void *) dns_hdr + query_length + sizeof(struct dns_response); 380 | if((void*) ar + sizeof(struct ar_hdr) > data_end){ 381 | #ifdef DEBUG 382 | bpf_printk("Error: boundary exceeded while parsing additional record"); 383 | #endif 384 | return -1; 385 | } 386 | 387 | return 0; 388 | } 389 | 390 | static inline int create_ar_response(struct ar_hdr *ar, char *dns_buffer, size_t *buf_size) 391 | { 392 | //Check for OPT record (RFC6891) 393 | if(ar->type == bpf_htons(41)){ 394 | #ifdef DEBUG 395 | bpf_printk("OPT record found"); 396 | #endif 397 | struct ar_hdr *ar_response = (struct ar_hdr *) &dns_buffer[0]; 398 | //We've received an OPT record, advertising the clients' UDP payload size 399 | //Respond that we're serving a payload size of 512 and not serving any additional records. 400 | ar_response->name = 0; 401 | ar_response->type = bpf_htons(41); 402 | ar_response->size = bpf_htons(512); 403 | ar_response->ex_rcode = 0; 404 | ar_response->rcode_len = 0; 405 | 406 | *buf_size += sizeof(struct ar_hdr); 407 | } 408 | else 409 | { 410 | return -1; 411 | } 412 | 413 | return 0; 414 | } 415 | #endif 416 | 417 | static void create_query_response(struct a_record *a, char *dns_buffer, size_t *buf_size) 418 | { 419 | //Formulate a DNS response. Currently defaults to hardcoded query pointer + type a + class in + ttl + 4 bytes as reply. 420 | struct dns_response *response = (struct dns_response *) &dns_buffer[0]; 421 | response->query_pointer = bpf_htons(0xc00c); 422 | response->record_type = bpf_htons(0x0001); 423 | response->class = bpf_htons(0x0001); 424 | response->ttl = bpf_htonl(a->ttl); 425 | response->data_length = bpf_htons((uint16_t)sizeof(a->ip_addr)); 426 | *buf_size += sizeof(struct dns_response); 427 | //Copy IP address 428 | __builtin_memcpy(&dns_buffer[*buf_size], &a->ip_addr, sizeof(struct in_addr)); 429 | *buf_size += sizeof(struct in_addr); 430 | } 431 | 432 | //Update IP checksum for IP header, as specified in RFC 1071 433 | //The checksum_location is passed as a pointer. At this location 16 bits need to be set to 0. 434 | static inline void update_ip_checksum(void *data, int len, uint16_t *checksum_location) 435 | { 436 | uint32_t accumulator = 0; 437 | int i; 438 | for (i = 0; i < len; i += 2) 439 | { 440 | uint16_t val; 441 | //If we are currently at the checksum_location, set to zero 442 | if (data + i == checksum_location) 443 | { 444 | val = 0; 445 | } 446 | else 447 | { 448 | //Else we load two bytes of data into val 449 | val = *(uint16_t *)(data + i); 450 | } 451 | accumulator += val; 452 | } 453 | 454 | //Add 16 bits overflow back to accumulator (if necessary) 455 | uint16_t overflow = accumulator >> 16; 456 | accumulator &= 0x00FFFF; 457 | accumulator += overflow; 458 | 459 | //If this resulted in an overflow again, do the same (if necessary) 460 | accumulator += (accumulator >> 16); 461 | accumulator &= 0x00FFFF; 462 | 463 | //Invert bits and set the checksum at checksum_location 464 | uint16_t chk = accumulator ^ 0xFFFF; 465 | 466 | #ifdef DEBUG 467 | bpf_printk("Checksum: %u", chk); 468 | #endif 469 | 470 | *checksum_location = chk; 471 | } 472 | 473 | static inline void modify_dns_header_response(struct dns_hdr *dns_hdr) 474 | { 475 | //Set query response 476 | dns_hdr->qr = 1; 477 | //Set truncated to 0 478 | //dns_hdr->tc = 0; 479 | //Set authorative to zero 480 | //dns_hdr->aa = 0; 481 | //Recursion available 482 | dns_hdr->ra = 1; 483 | //One answer 484 | dns_hdr->ans_count = bpf_htons(1); 485 | } 486 | 487 | //__builtin_memcpy only supports static size_t 488 | //The following function is a memcpy wrapper that uses __builtin_memcpy when size_t n is known. 489 | //Otherwise it uses our own naive & slow memcpy routine 490 | static inline void copy_to_pkt_buf(struct xdp_md *ctx, void *dst, void *src, size_t n) 491 | { 492 | //Boundary check 493 | if((void *)(long)ctx->data_end >= dst + n){ 494 | int i; 495 | char *cdst = dst; 496 | char *csrc = src; 497 | 498 | //For A records, src is either 16 or 27 bytes, depending if OPT record is requested. 499 | //Use __builtin_memcpy for this. Otherwise, use our own slow, naive memcpy implementation. 500 | switch(n) 501 | { 502 | case 16: 503 | __builtin_memcpy(cdst, csrc, 16); 504 | break; 505 | 506 | case 27: 507 | __builtin_memcpy(cdst, csrc, 27); 508 | break; 509 | 510 | default: 511 | for(i = 0; i < n; i+=1) 512 | { 513 | cdst[i] = csrc[i]; 514 | } 515 | } 516 | } 517 | } 518 | 519 | static inline void swap_mac(uint8_t *src_mac, uint8_t *dst_mac) 520 | { 521 | int i; 522 | for (i = 0; i < 6; i++) 523 | { 524 | uint8_t tmp_src; 525 | tmp_src = *(src_mac + i); 526 | *(src_mac + i) = *(dst_mac + i); 527 | *(dst_mac + i) = tmp_src; 528 | } 529 | } 530 | 531 | #ifndef BCC_SEC 532 | char _license[] SEC("license") = "GPL"; 533 | __u32 _version SEC("version") = LINUX_VERSION_CODE; 534 | #endif 535 | --------------------------------------------------------------------------------