xref: /linux/tools/testing/selftests/bpf/progs/socket_cookie_prog.c (revision 31d166642c7c601c65eccf0ff2e0afe9a0538be2)
1 // SPDX-License-Identifier: GPL-2.0
2 // Copyright (c) 2018 Facebook
3 
4 #include <linux/bpf.h>
5 #include <sys/socket.h>
6 
7 #include "bpf_helpers.h"
8 #include "bpf_endian.h"
9 
10 struct socket_cookie {
11 	__u64 cookie_key;
12 	__u32 cookie_value;
13 };
14 
15 struct {
16 	__u32 type;
17 	__u32 map_flags;
18 	int *key;
19 	struct socket_cookie *value;
20 } socket_cookies SEC(".maps") = {
21 	.type = BPF_MAP_TYPE_SK_STORAGE,
22 	.map_flags = BPF_F_NO_PREALLOC,
23 };
24 
25 SEC("cgroup/connect6")
26 int set_cookie(struct bpf_sock_addr *ctx)
27 {
28 	struct socket_cookie *p;
29 
30 	if (ctx->family != AF_INET6 || ctx->user_family != AF_INET6)
31 		return 1;
32 
33 	p = bpf_sk_storage_get(&socket_cookies, ctx->sk, 0,
34 			       BPF_SK_STORAGE_GET_F_CREATE);
35 	if (!p)
36 		return 1;
37 
38 	p->cookie_value = 0xFF;
39 	p->cookie_key = bpf_get_socket_cookie(ctx);
40 
41 	return 1;
42 }
43 
44 SEC("sockops")
45 int update_cookie(struct bpf_sock_ops *ctx)
46 {
47 	struct bpf_sock *sk;
48 	struct socket_cookie *p;
49 
50 	if (ctx->family != AF_INET6)
51 		return 1;
52 
53 	if (ctx->op != BPF_SOCK_OPS_TCP_CONNECT_CB)
54 		return 1;
55 
56 	if (!ctx->sk)
57 		return 1;
58 
59 	p = bpf_sk_storage_get(&socket_cookies, ctx->sk, 0, 0);
60 	if (!p)
61 		return 1;
62 
63 	if (p->cookie_key != bpf_get_socket_cookie(ctx))
64 		return 1;
65 
66 	p->cookie_value = (ctx->local_port << 8) | p->cookie_value;
67 
68 	return 1;
69 }
70 
71 int _version SEC("version") = 1;
72 
73 char _license[] SEC("license") = "GPL";
74