Tyler Wear | b37f551 | 2021-10-01 13:22:00 -0700 | [diff] [blame] | 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 | |
Maciej Żenczykowski | fa61d49 | 2022-05-16 16:05:15 -0700 | [diff] [blame] | 22 | // The resulting .o needs to load on the Android T bpfloader v0.12+ |
| 23 | #define BPFLOADER_MIN_VER 12u |
| 24 | |
Tyler Wear | b37f551 | 2021-10-01 13:22:00 -0700 | [diff] [blame] | 25 | #include "bpf_helpers.h" |
| 26 | |
| 27 | #define ALLOW 1 |
| 28 | #define DISALLOW 0 |
| 29 | |
| 30 | DEFINE_BPF_MAP_GRW(blocked_ports_map, ARRAY, int, uint64_t, |
| 31 | 1024 /* 64K ports -> 1024 u64s */, AID_SYSTEM) |
| 32 | |
| 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 | DEFINE_BPF_PROG_KVER("bind4/block_port", AID_ROOT, AID_SYSTEM, |
| 61 | bind4_block_port, KVER(5, 4, 0)) |
| 62 | (struct bpf_sock_addr *ctx) { |
| 63 | return block_port(ctx); |
| 64 | } |
| 65 | |
| 66 | DEFINE_BPF_PROG_KVER("bind6/block_port", AID_ROOT, AID_SYSTEM, |
| 67 | bind6_block_port, KVER(5, 4, 0)) |
| 68 | (struct bpf_sock_addr *ctx) { |
| 69 | return block_port(ctx); |
| 70 | } |
| 71 | |
| 72 | LICENSE("Apache 2.0"); |
| 73 | CRITICAL("ConnectivityNative"); |