blob: ddd9a1cbedf077ea9b2571871075eb41e0ecd0fe [file] [log] [blame]
Tyler Wearb37f5512021-10-01 13:22:00 -07001/*
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#include "bpf_helpers.h"
23
24#define ALLOW 1
25#define DISALLOW 0
26
27DEFINE_BPF_MAP_GRW(blocked_ports_map, ARRAY, int, uint64_t,
28 1024 /* 64K ports -> 1024 u64s */, AID_SYSTEM)
29
30static inline __always_inline int block_port(struct bpf_sock_addr *ctx) {
31 if (!ctx->user_port) return ALLOW;
32
33 switch (ctx->protocol) {
34 case IPPROTO_TCP:
35 case IPPROTO_MPTCP:
36 case IPPROTO_UDP:
37 case IPPROTO_UDPLITE:
38 case IPPROTO_DCCP:
39 case IPPROTO_SCTP:
40 break;
41 default:
42 return ALLOW; // unknown protocols are allowed
43 }
44
45 int key = ctx->user_port >> 6;
46 int shift = ctx->user_port & 63;
47
48 uint64_t *val = bpf_blocked_ports_map_lookup_elem(&key);
49 // Lookup should never fail in reality, but if it does return here to keep the
50 // BPF verifier happy.
51 if (!val) return ALLOW;
52
53 if ((*val >> shift) & 1) return DISALLOW;
54 return ALLOW;
55}
56
57DEFINE_BPF_PROG_KVER("bind4/block_port", AID_ROOT, AID_SYSTEM,
58 bind4_block_port, KVER(5, 4, 0))
59(struct bpf_sock_addr *ctx) {
60 return block_port(ctx);
61}
62
63DEFINE_BPF_PROG_KVER("bind6/block_port", AID_ROOT, AID_SYSTEM,
64 bind6_block_port, KVER(5, 4, 0))
65(struct bpf_sock_addr *ctx) {
66 return block_port(ctx);
67}
68
69LICENSE("Apache 2.0");
70CRITICAL("ConnectivityNative");