1 /*
2 * Copyright (C) 2022 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include <linux/types.h>
18 #include <linux/bpf.h>
19 #include <netinet/in.h>
20 #include <stdint.h>
21
22 // The resulting .o needs to load on Android T+
23 #define BPFLOADER_MIN_VER BPFLOADER_T_VERSION
24
25 #include "bpf_helpers.h"
26
27 static const int ALLOW = 1;
28 static const int DISALLOW = 0;
29
30 DEFINE_BPF_MAP_GRW(blocked_ports_map, ARRAY, int, uint64_t,
31 1024 /* 64K ports -> 1024 u64s */, AID_SYSTEM)
32
block_port(struct bpf_sock_addr * ctx)33 static inline __always_inline int block_port(struct bpf_sock_addr *ctx) {
34 if (!ctx->user_port) return ALLOW;
35
36 switch (ctx->protocol) {
37 case IPPROTO_TCP:
38 case IPPROTO_MPTCP:
39 case IPPROTO_UDP:
40 case IPPROTO_UDPLITE:
41 case IPPROTO_DCCP:
42 case IPPROTO_SCTP:
43 break;
44 default:
45 return ALLOW; // unknown protocols are allowed
46 }
47
48 int key = ctx->user_port >> 6;
49 int shift = ctx->user_port & 63;
50
51 uint64_t *val = bpf_blocked_ports_map_lookup_elem(&key);
52 // Lookup should never fail in reality, but if it does return here to keep the
53 // BPF verifier happy.
54 if (!val) return ALLOW;
55
56 if ((*val >> shift) & 1) return DISALLOW;
57 return ALLOW;
58 }
59
60 // the program need to be accessible/loadable by netd (from netd updatable plugin)
61 #define DEFINE_NETD_RO_BPF_PROG(SECTION_NAME, the_prog, min_kver) \
62 DEFINE_BPF_PROG_EXT(SECTION_NAME, AID_ROOT, AID_ROOT, the_prog, min_kver, KVER_INF, \
63 BPFLOADER_MIN_VER, BPFLOADER_MAX_VER, MANDATORY, \
64 "", "netd_readonly/", LOAD_ON_ENG, LOAD_ON_USER, LOAD_ON_USERDEBUG)
65
66 DEFINE_NETD_RO_BPF_PROG("bind4/block_port", bind4_block_port, KVER_4_19)
67 (struct bpf_sock_addr *ctx) {
68 return block_port(ctx);
69 }
70
71 DEFINE_NETD_RO_BPF_PROG("bind6/block_port", bind6_block_port, KVER_4_19)
72 (struct bpf_sock_addr *ctx) {
73 return block_port(ctx);
74 }
75
76 LICENSE("Apache 2.0");
77 CRITICAL("ConnectivityNative");
78 DISABLE_BTF_ON_USER_BUILDS();
79 DISABLE_ON_MAINLINE_BEFORE_U_QPR3();
80