selftests/bpf: Selftest for sys_bind hooks
[muen/linux.git] / tools / testing / selftests / bpf / test_sock_addr.c
1 // SPDX-License-Identifier: GPL-2.0
2 // Copyright (c) 2018 Facebook
3
4 #include <stdio.h>
5 #include <stdlib.h>
6 #include <unistd.h>
7
8 #include <arpa/inet.h>
9 #include <sys/types.h>
10 #include <sys/socket.h>
11
12 #include <linux/filter.h>
13
14 #include <bpf/bpf.h>
15
16 #include "cgroup_helpers.h"
17
18 #define CG_PATH "/foo"
19
20 #define SERV4_IP                "192.168.1.254"
21 #define SERV4_REWRITE_IP        "127.0.0.1"
22 #define SERV4_PORT              4040
23 #define SERV4_REWRITE_PORT      4444
24
25 #define SERV6_IP                "face:b00c:1234:5678::abcd"
26 #define SERV6_REWRITE_IP        "::1"
27 #define SERV6_PORT              6060
28 #define SERV6_REWRITE_PORT      6666
29
30 #define INET_NTOP_BUF   40
31
32 typedef int (*load_fn)(enum bpf_attach_type, const char *comment);
33 typedef int (*info_fn)(int, struct sockaddr *, socklen_t *);
34
35 struct program {
36         enum bpf_attach_type type;
37         load_fn loadfn;
38         int fd;
39         const char *name;
40         enum bpf_attach_type invalid_type;
41 };
42
43 char bpf_log_buf[BPF_LOG_BUF_SIZE];
44
45 static int mk_sockaddr(int domain, const char *ip, unsigned short port,
46                        struct sockaddr *addr, socklen_t addr_len)
47 {
48         struct sockaddr_in6 *addr6;
49         struct sockaddr_in *addr4;
50
51         if (domain != AF_INET && domain != AF_INET6) {
52                 log_err("Unsupported address family");
53                 return -1;
54         }
55
56         memset(addr, 0, addr_len);
57
58         if (domain == AF_INET) {
59                 if (addr_len < sizeof(struct sockaddr_in))
60                         return -1;
61                 addr4 = (struct sockaddr_in *)addr;
62                 addr4->sin_family = domain;
63                 addr4->sin_port = htons(port);
64                 if (inet_pton(domain, ip, (void *)&addr4->sin_addr) != 1) {
65                         log_err("Invalid IPv4: %s", ip);
66                         return -1;
67                 }
68         } else if (domain == AF_INET6) {
69                 if (addr_len < sizeof(struct sockaddr_in6))
70                         return -1;
71                 addr6 = (struct sockaddr_in6 *)addr;
72                 addr6->sin6_family = domain;
73                 addr6->sin6_port = htons(port);
74                 if (inet_pton(domain, ip, (void *)&addr6->sin6_addr) != 1) {
75                         log_err("Invalid IPv6: %s", ip);
76                         return -1;
77                 }
78         }
79
80         return 0;
81 }
82
83 static int load_insns(enum bpf_attach_type attach_type,
84                       const struct bpf_insn *insns, size_t insns_cnt,
85                       const char *comment)
86 {
87         struct bpf_load_program_attr load_attr;
88         int ret;
89
90         memset(&load_attr, 0, sizeof(struct bpf_load_program_attr));
91         load_attr.prog_type = BPF_PROG_TYPE_CGROUP_SOCK_ADDR;
92         load_attr.expected_attach_type = attach_type;
93         load_attr.insns = insns;
94         load_attr.insns_cnt = insns_cnt;
95         load_attr.license = "GPL";
96
97         ret = bpf_load_program_xattr(&load_attr, bpf_log_buf, BPF_LOG_BUF_SIZE);
98         if (ret < 0 && comment) {
99                 log_err(">>> Loading %s program error.\n"
100                         ">>> Output from verifier:\n%s\n-------\n",
101                         comment, bpf_log_buf);
102         }
103
104         return ret;
105 }
106
107 /* [1] These testing programs try to read different context fields, including
108  * narrow loads of different sizes from user_ip4 and user_ip6, and write to
109  * those allowed to be overridden.
110  *
111  * [2] BPF_LD_IMM64 & BPF_JMP_REG are used below whenever there is a need to
112  * compare a register with unsigned 32bit integer. BPF_JMP_IMM can't be used
113  * in such cases since it accepts only _signed_ 32bit integer as IMM
114  * argument. Also note that BPF_LD_IMM64 contains 2 instructions what matters
115  * to count jumps properly.
116  */
117
118 static int bind4_prog_load(enum bpf_attach_type attach_type,
119                            const char *comment)
120 {
121         union {
122                 uint8_t u4_addr8[4];
123                 uint16_t u4_addr16[2];
124                 uint32_t u4_addr32;
125         } ip4;
126         struct sockaddr_in addr4_rw;
127
128         if (inet_pton(AF_INET, SERV4_IP, (void *)&ip4) != 1) {
129                 log_err("Invalid IPv4: %s", SERV4_IP);
130                 return -1;
131         }
132
133         if (mk_sockaddr(AF_INET, SERV4_REWRITE_IP, SERV4_REWRITE_PORT,
134                         (struct sockaddr *)&addr4_rw, sizeof(addr4_rw)) == -1)
135                 return -1;
136
137         /* See [1]. */
138         struct bpf_insn insns[] = {
139                 BPF_MOV64_REG(BPF_REG_6, BPF_REG_1),
140
141                 /* if (sk.family == AF_INET && */
142                 BPF_LDX_MEM(BPF_W, BPF_REG_7, BPF_REG_6,
143                             offsetof(struct bpf_sock_addr, family)),
144                 BPF_JMP_IMM(BPF_JNE, BPF_REG_7, AF_INET, 16),
145
146                 /*     (sk.type == SOCK_DGRAM || sk.type == SOCK_STREAM) && */
147                 BPF_LDX_MEM(BPF_W, BPF_REG_7, BPF_REG_6,
148                             offsetof(struct bpf_sock_addr, type)),
149                 BPF_JMP_IMM(BPF_JNE, BPF_REG_7, SOCK_DGRAM, 1),
150                 BPF_JMP_A(1),
151                 BPF_JMP_IMM(BPF_JNE, BPF_REG_7, SOCK_STREAM, 12),
152
153                 /*     1st_byte_of_user_ip4 == expected && */
154                 BPF_LDX_MEM(BPF_B, BPF_REG_7, BPF_REG_6,
155                             offsetof(struct bpf_sock_addr, user_ip4)),
156                 BPF_JMP_IMM(BPF_JNE, BPF_REG_7, ip4.u4_addr8[0], 10),
157
158                 /*     1st_half_of_user_ip4 == expected && */
159                 BPF_LDX_MEM(BPF_H, BPF_REG_7, BPF_REG_6,
160                             offsetof(struct bpf_sock_addr, user_ip4)),
161                 BPF_JMP_IMM(BPF_JNE, BPF_REG_7, ip4.u4_addr16[0], 8),
162
163                 /*     whole_user_ip4 == expected) { */
164                 BPF_LDX_MEM(BPF_W, BPF_REG_7, BPF_REG_6,
165                             offsetof(struct bpf_sock_addr, user_ip4)),
166                 BPF_LD_IMM64(BPF_REG_8, ip4.u4_addr32), /* See [2]. */
167                 BPF_JMP_REG(BPF_JNE, BPF_REG_7, BPF_REG_8, 4),
168
169                 /*      user_ip4 = addr4_rw.sin_addr */
170                 BPF_MOV32_IMM(BPF_REG_7, addr4_rw.sin_addr.s_addr),
171                 BPF_STX_MEM(BPF_W, BPF_REG_6, BPF_REG_7,
172                             offsetof(struct bpf_sock_addr, user_ip4)),
173
174                 /*      user_port = addr4_rw.sin_port */
175                 BPF_MOV32_IMM(BPF_REG_7, addr4_rw.sin_port),
176                 BPF_STX_MEM(BPF_W, BPF_REG_6, BPF_REG_7,
177                             offsetof(struct bpf_sock_addr, user_port)),
178                 /* } */
179
180                 /* return 1 */
181                 BPF_MOV64_IMM(BPF_REG_0, 1),
182                 BPF_EXIT_INSN(),
183         };
184
185         return load_insns(attach_type, insns,
186                           sizeof(insns) / sizeof(struct bpf_insn), comment);
187 }
188
189 static int bind6_prog_load(enum bpf_attach_type attach_type,
190                            const char *comment)
191 {
192         struct sockaddr_in6 addr6_rw;
193         struct in6_addr ip6;
194
195         if (inet_pton(AF_INET6, SERV6_IP, (void *)&ip6) != 1) {
196                 log_err("Invalid IPv6: %s", SERV6_IP);
197                 return -1;
198         }
199
200         if (mk_sockaddr(AF_INET6, SERV6_REWRITE_IP, SERV6_REWRITE_PORT,
201                         (struct sockaddr *)&addr6_rw, sizeof(addr6_rw)) == -1)
202                 return -1;
203
204         /* See [1]. */
205         struct bpf_insn insns[] = {
206                 BPF_MOV64_REG(BPF_REG_6, BPF_REG_1),
207
208                 /* if (sk.family == AF_INET6 && */
209                 BPF_LDX_MEM(BPF_W, BPF_REG_7, BPF_REG_6,
210                             offsetof(struct bpf_sock_addr, family)),
211                 BPF_JMP_IMM(BPF_JNE, BPF_REG_7, AF_INET6, 18),
212
213                 /*            5th_byte_of_user_ip6 == expected && */
214                 BPF_LDX_MEM(BPF_B, BPF_REG_7, BPF_REG_6,
215                             offsetof(struct bpf_sock_addr, user_ip6[1])),
216                 BPF_JMP_IMM(BPF_JNE, BPF_REG_7, ip6.s6_addr[4], 16),
217
218                 /*            3rd_half_of_user_ip6 == expected && */
219                 BPF_LDX_MEM(BPF_H, BPF_REG_7, BPF_REG_6,
220                             offsetof(struct bpf_sock_addr, user_ip6[1])),
221                 BPF_JMP_IMM(BPF_JNE, BPF_REG_7, ip6.s6_addr16[2], 14),
222
223                 /*            last_word_of_user_ip6 == expected) { */
224                 BPF_LDX_MEM(BPF_W, BPF_REG_7, BPF_REG_6,
225                             offsetof(struct bpf_sock_addr, user_ip6[3])),
226                 BPF_LD_IMM64(BPF_REG_8, ip6.s6_addr32[3]),  /* See [2]. */
227                 BPF_JMP_REG(BPF_JNE, BPF_REG_7, BPF_REG_8, 10),
228
229
230 #define STORE_IPV6_WORD(N)                                                     \
231                 BPF_MOV32_IMM(BPF_REG_7, addr6_rw.sin6_addr.s6_addr32[N]),     \
232                 BPF_STX_MEM(BPF_W, BPF_REG_6, BPF_REG_7,                       \
233                             offsetof(struct bpf_sock_addr, user_ip6[N]))
234
235                 /*      user_ip6 = addr6_rw.sin6_addr */
236                 STORE_IPV6_WORD(0),
237                 STORE_IPV6_WORD(1),
238                 STORE_IPV6_WORD(2),
239                 STORE_IPV6_WORD(3),
240
241                 /*      user_port = addr6_rw.sin6_port */
242                 BPF_MOV32_IMM(BPF_REG_7, addr6_rw.sin6_port),
243                 BPF_STX_MEM(BPF_W, BPF_REG_6, BPF_REG_7,
244                             offsetof(struct bpf_sock_addr, user_port)),
245
246                 /* } */
247
248                 /* return 1 */
249                 BPF_MOV64_IMM(BPF_REG_0, 1),
250                 BPF_EXIT_INSN(),
251         };
252
253         return load_insns(attach_type, insns,
254                           sizeof(insns) / sizeof(struct bpf_insn), comment);
255 }
256
257 static void print_ip_port(int sockfd, info_fn fn, const char *fmt)
258 {
259         char addr_buf[INET_NTOP_BUF];
260         struct sockaddr_storage addr;
261         struct sockaddr_in6 *addr6;
262         struct sockaddr_in *addr4;
263         socklen_t addr_len;
264         unsigned short port;
265         void *nip;
266
267         addr_len = sizeof(struct sockaddr_storage);
268         memset(&addr, 0, addr_len);
269
270         if (fn(sockfd, (struct sockaddr *)&addr, (socklen_t *)&addr_len) == 0) {
271                 if (addr.ss_family == AF_INET) {
272                         addr4 = (struct sockaddr_in *)&addr;
273                         nip = (void *)&addr4->sin_addr;
274                         port = ntohs(addr4->sin_port);
275                 } else if (addr.ss_family == AF_INET6) {
276                         addr6 = (struct sockaddr_in6 *)&addr;
277                         nip = (void *)&addr6->sin6_addr;
278                         port = ntohs(addr6->sin6_port);
279                 } else {
280                         return;
281                 }
282                 const char *addr_str =
283                         inet_ntop(addr.ss_family, nip, addr_buf, INET_NTOP_BUF);
284                 printf(fmt, addr_str ? addr_str : "??", port);
285         }
286 }
287
288 static void print_local_ip_port(int sockfd, const char *fmt)
289 {
290         print_ip_port(sockfd, getsockname, fmt);
291 }
292
293 static int start_server(int type, const struct sockaddr_storage *addr,
294                         socklen_t addr_len)
295 {
296
297         int fd;
298
299         fd = socket(addr->ss_family, type, 0);
300         if (fd == -1) {
301                 log_err("Failed to create server socket");
302                 goto out;
303         }
304
305         if (bind(fd, (const struct sockaddr *)addr, addr_len) == -1) {
306                 log_err("Failed to bind server socket");
307                 goto close_out;
308         }
309
310         if (type == SOCK_STREAM) {
311                 if (listen(fd, 128) == -1) {
312                         log_err("Failed to listen on server socket");
313                         goto close_out;
314                 }
315         }
316
317         print_local_ip_port(fd, "\t   Actual: bind(%s, %d)\n");
318
319         goto out;
320 close_out:
321         close(fd);
322         fd = -1;
323 out:
324         return fd;
325 }
326
327 static void print_test_case_num(int domain, int type)
328 {
329         static int test_num;
330
331         printf("Test case #%d (%s/%s):\n", ++test_num,
332                (domain == AF_INET ? "IPv4" :
333                 domain == AF_INET6 ? "IPv6" :
334                 "unknown_domain"),
335                (type == SOCK_STREAM ? "TCP" :
336                 type == SOCK_DGRAM ? "UDP" :
337                 "unknown_type"));
338 }
339
340 static int run_test_case(int domain, int type, const char *ip,
341                          unsigned short port)
342 {
343         struct sockaddr_storage addr;
344         socklen_t addr_len = sizeof(addr);
345         int servfd = -1;
346         int err = 0;
347
348         print_test_case_num(domain, type);
349
350         if (mk_sockaddr(domain, ip, port, (struct sockaddr *)&addr,
351                         addr_len) == -1)
352                 return -1;
353
354         printf("\tRequested: bind(%s, %d) ..\n", ip, port);
355         servfd = start_server(type, &addr, addr_len);
356         if (servfd == -1)
357                 goto err;
358
359         goto out;
360 err:
361         err = -1;
362 out:
363         close(servfd);
364         return err;
365 }
366
367 static void close_progs_fds(struct program *progs, size_t prog_cnt)
368 {
369         size_t i;
370
371         for (i = 0; i < prog_cnt; ++i) {
372                 close(progs[i].fd);
373                 progs[i].fd = -1;
374         }
375 }
376
377 static int load_and_attach_progs(int cgfd, struct program *progs,
378                                  size_t prog_cnt)
379 {
380         size_t i;
381
382         for (i = 0; i < prog_cnt; ++i) {
383                 progs[i].fd = progs[i].loadfn(progs[i].invalid_type, NULL);
384                 if (progs[i].fd != -1) {
385                         log_err("Load with invalid type accepted for %s",
386                                 progs[i].name);
387                         goto err;
388                 }
389                 progs[i].fd = progs[i].loadfn(progs[i].type, progs[i].name);
390                 if (progs[i].fd == -1) {
391                         log_err("Failed to load program %s", progs[i].name);
392                         goto err;
393                 }
394                 if (bpf_prog_attach(progs[i].fd, cgfd, progs[i].invalid_type,
395                                     BPF_F_ALLOW_OVERRIDE) != -1) {
396                         log_err("Attach with invalid type accepted for %s",
397                                 progs[i].name);
398                         goto err;
399                 }
400                 if (bpf_prog_attach(progs[i].fd, cgfd, progs[i].type,
401                                     BPF_F_ALLOW_OVERRIDE) == -1) {
402                         log_err("Failed to attach program %s", progs[i].name);
403                         goto err;
404                 }
405                 printf("Attached %s program.\n", progs[i].name);
406         }
407
408         return 0;
409 err:
410         close_progs_fds(progs, prog_cnt);
411         return -1;
412 }
413
414 static int run_domain_test(int domain, int cgfd, struct program *progs,
415                            size_t prog_cnt, const char *ip, unsigned short port)
416 {
417         int err = 0;
418
419         if (load_and_attach_progs(cgfd, progs, prog_cnt) == -1)
420                 goto err;
421
422         if (run_test_case(domain, SOCK_STREAM, ip, port) == -1)
423                 goto err;
424
425         if (run_test_case(domain, SOCK_DGRAM, ip, port) == -1)
426                 goto err;
427
428         goto out;
429 err:
430         err = -1;
431 out:
432         close_progs_fds(progs, prog_cnt);
433         return err;
434 }
435
436 static int run_test(void)
437 {
438         size_t inet6_prog_cnt;
439         size_t inet_prog_cnt;
440         int cgfd = -1;
441         int err = 0;
442
443         struct program inet6_progs[] = {
444                 {BPF_CGROUP_INET6_BIND, bind6_prog_load, -1, "bind6",
445                  BPF_CGROUP_INET4_BIND},
446         };
447         inet6_prog_cnt = sizeof(inet6_progs) / sizeof(struct program);
448
449         struct program inet_progs[] = {
450                 {BPF_CGROUP_INET4_BIND, bind4_prog_load, -1, "bind4",
451                  BPF_CGROUP_INET6_BIND},
452         };
453         inet_prog_cnt = sizeof(inet_progs) / sizeof(struct program);
454
455         if (setup_cgroup_environment())
456                 goto err;
457
458         cgfd = create_and_get_cgroup(CG_PATH);
459         if (!cgfd)
460                 goto err;
461
462         if (join_cgroup(CG_PATH))
463                 goto err;
464
465         if (run_domain_test(AF_INET, cgfd, inet_progs, inet_prog_cnt, SERV4_IP,
466                             SERV4_PORT) == -1)
467                 goto err;
468
469         if (run_domain_test(AF_INET6, cgfd, inet6_progs, inet6_prog_cnt,
470                             SERV6_IP, SERV6_PORT) == -1)
471                 goto err;
472
473         goto out;
474 err:
475         err = -1;
476 out:
477         close(cgfd);
478         cleanup_cgroup_environment();
479         printf(err ? "### FAIL\n" : "### SUCCESS\n");
480         return err;
481 }
482
483 int main(int argc, char **argv)
484 {
485         return run_test();
486 }