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 bpf_map_def SEC("maps") socket_cookies = {
11 	.type = BPF_MAP_TYPE_HASH,
12 	.key_size = sizeof(__u64),
13 	.value_size = sizeof(__u32),
14 	.max_entries = 1 << 8,
15 };
16 
17 SEC("cgroup/connect6")
18 int set_cookie(struct bpf_sock_addr *ctx)
19 {
20 	__u32 cookie_value = 0xFF;
21 	__u64 cookie_key;
22 
23 	if (ctx->family != AF_INET6 || ctx->user_family != AF_INET6)
24 		return 1;
25 
26 	cookie_key = bpf_get_socket_cookie(ctx);
27 	if (bpf_map_update_elem(&socket_cookies, &cookie_key, &cookie_value, 0))
28 		return 0;
29 
30 	return 1;
31 }
32 
33 SEC("sockops")
34 int update_cookie(struct bpf_sock_ops *ctx)
35 {
36 	__u32 new_cookie_value;
37 	__u32 *cookie_value;
38 	__u64 cookie_key;
39 
40 	if (ctx->family != AF_INET6)
41 		return 1;
42 
43 	if (ctx->op != BPF_SOCK_OPS_TCP_CONNECT_CB)
44 		return 1;
45 
46 	cookie_key = bpf_get_socket_cookie(ctx);
47 
48 	cookie_value = bpf_map_lookup_elem(&socket_cookies, &cookie_key);
49 	if (!cookie_value)
50 		return 1;
51 
52 	new_cookie_value = (ctx->local_port << 8) | *cookie_value;
53 	bpf_map_update_elem(&socket_cookies, &cookie_key, &new_cookie_value, 0);
54 
55 	return 1;
56 }
57 
58 int _version SEC("version") = 1;
59 
60 char _license[] SEC("license") = "GPL";
61