-
Notifications
You must be signed in to change notification settings - Fork 12
/
Firewall.java
231 lines (208 loc) · 8.63 KB
/
Firewall.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
package me.bechberger.ebpf.samples;
import me.bechberger.ebpf.annotations.AlwaysInline;
import me.bechberger.ebpf.annotations.Type;
import me.bechberger.ebpf.annotations.Unsigned;
import me.bechberger.ebpf.annotations.bpf.BPF;
import me.bechberger.ebpf.annotations.bpf.BPFFunction;
import me.bechberger.ebpf.annotations.bpf.BPFMapDefinition;
import me.bechberger.ebpf.bpf.*;
import me.bechberger.ebpf.bpf.map.BPFHashMap;
import me.bechberger.ebpf.bpf.map.BPFLRUHashMap;
import me.bechberger.ebpf.bpf.map.BPFRingBuffer;
import me.bechberger.ebpf.type.Enum;
import me.bechberger.ebpf.type.Ptr;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static me.bechberger.ebpf.bpf.BPFJ.bpf_trace_printk;
import static me.bechberger.ebpf.runtime.XdpDefinitions.*;
import static me.bechberger.ebpf.runtime.helpers.BPFHelpers.bpf_ktime_get_ns;
@BPF(license = "GPL")
public abstract class Firewall extends BPFProgram implements XDPHook, BasePacketParser {
private static final Logger logger = LoggerFactory.getLogger(Firewall.class);
@Type
record IPAndPort(int ip, int sourcePort, int destPort) {
}
@Type
record LogEntry(IPAndPort connection, long timeInMs) {
}
@Type
record FirewallRule(@Unsigned int ip,
int ignoreLowBytes,
int sourcePort,
int destPort) {
}
@Type
enum FirewallAction implements Enum<FirewallAction> {
ALLOW, DROP, NONE
}
@BPFMapDefinition(maxEntries = 1000)
BPFHashMap<FirewallRule, FirewallAction> firewallRules;
@BPFMapDefinition(maxEntries = 1000)
BPFLRUHashMap<IPAndPort, Long> connectionCount;
@BPFMapDefinition(maxEntries = 1000 * 128)
BPFRingBuffer<LogEntry> blockedConnections;
@BPFMapDefinition(maxEntries = 1000)
BPFLRUHashMap<IPAndPort, FirewallAction> resolvedRules;
@BPFFunction
@AlwaysInline
static int zeroLowBytes(int ip, int ignoreLowBytes) {
return ip & (0xFFFFFFFF << (ignoreLowBytes * 8));
}
@BPFFunction
@AlwaysInline
FirewallAction computeSpecificAction(Ptr<IPAndPort> info, int ignoreLowBytes) {
int ip = info.val().ip;
var sourcePort = info.val().sourcePort;
var destPort = info.val().destPort;
// first null the bytes that should be ignored
int matchingAddressBytes = zeroLowBytes(ip, ignoreLowBytes);
if (matchingAddressBytes == 0) { // don't ask
bpf_trace_printk("Checking rule for %d:%d\n", matchingAddressBytes, sourcePort);
}
var rule = new FirewallRule(matchingAddressBytes, ignoreLowBytes, sourcePort, destPort);
var action = firewallRules.bpf_get(rule);
if (action != null) {
return action.val();
}
rule = new FirewallRule(matchingAddressBytes, ignoreLowBytes, sourcePort, -1);
action = firewallRules.bpf_get(rule);
if (action != null) {
return action.val();
}
rule = new FirewallRule(matchingAddressBytes, ignoreLowBytes, -1, destPort);
action = firewallRules.bpf_get(rule);
if (action != null) {
return action.val();
}
rule = new FirewallRule(matchingAddressBytes, ignoreLowBytes, -1, -1);
action = firewallRules.bpf_get(rule);
if (action != null) {
return action.val();
}
return FirewallAction.NONE;
}
@BPFFunction
@AlwaysInline
FirewallAction computeAction(Ptr<IPAndPort> info) {
// for all possible ip address matching bytes, check if there is a rule for port or without port
for (int i = 0; i < 5; i++) {
var action = computeSpecificAction(info, i);
if (action != FirewallAction.NONE) {
return action;
}
}
return FirewallAction.NONE;
}
@BPFFunction
@AlwaysInline
FirewallAction getAction(Ptr<PacketInfo> packetInfo) {
IPAndPort ipAndPort = new IPAndPort(
packetInfo.val().source.ipv4(), packetInfo.val().sourcePort, packetInfo.val().destinationPort);
Ptr<FirewallAction> action = resolvedRules.bpf_get(ipAndPort);
if (action != null) {
return action.val();
}
var newAction = computeAction(Ptr.of(ipAndPort));
bpf_trace_printk("Unresolved action for %d:%d %d\n", ipAndPort.ip(), ipAndPort.sourcePort, newAction.value());
resolvedRules.put(ipAndPort, newAction);
return newAction;
}
@BPFFunction
@AlwaysInline
void countConnection(PacketInfo info) {
IPAndPort ipAndPort = new IPAndPort(info.source.ipv4(), info.sourcePort, info.destinationPort);
Ptr<Long> count = connectionCount.bpf_get(ipAndPort);
if (count == null) {
long one = 1;
connectionCount.put(ipAndPort, one);
} else {
count.set(count.val() + 1);
}
}
@BPFFunction
void recordBlockedConnection(PacketInfo info) {
Ptr<LogEntry> ptr = blockedConnections.reserve();
if (ptr == null) {
return;
}
ptr.set(
new LogEntry(new IPAndPort(info.source.ipv4(), info.sourcePort, info.destinationPort),
bpf_ktime_get_ns() / 1000000));
blockedConnections.submit(ptr);
}
@Override
public xdp_action xdpHandlePacket(Ptr<xdp_md> ctx) {
PacketInfo info = new PacketInfo();
info.direction = PacketDirection.INCOMING;
if (parsePacket2(ctx.val().data, ctx.val().data_end, Ptr.of(info))) {
countConnection(info);
var action = getAction(Ptr.of(info));
if (action == FirewallAction.DROP) {
recordBlockedConnection(info);
return xdp_action.XDP_DROP;
}
}
return xdp_action.XDP_PASS;
}
private static int parsePort(String port) {
return switch (port) {
case "HTTP" -> HTTP_PORT;
case "HTTPS" -> HTTPS_PORT;
case "ANY" -> -1;
default -> Integer.parseInt(port);
};
}
record FirewallRuleAndAction(FirewallRule rule, FirewallAction action) {
}
static FirewallRuleAndAction parseRule(String rule) {
FirewallRule firewallRule;
var rulePart = rule.split(" ")[0];
if (rule.contains("/")) {
if (!rulePart.matches(".*/(0|8|16|32):.*(:.*)?")) {
throw new IllegalArgumentException("Invalid rule: " + rule + ", should match .*/(0|8|16|32):.*(:.*)?");
}
String[] parts = rulePart.split(":");
String[] ipParts = parts[0].split("/");
int ip = NetworkUtil.ipAddressToInt(ipParts[0]);
int ignoreLowBytes = 32 - Integer.parseInt(ipParts[1]) / 8;
int sourcePort = parsePort(parts[1]);
int targetPort = parts.length == 3 ? parsePort(parts[2]) : -1;
firewallRule = new FirewallRule(zeroLowBytes(ip, ignoreLowBytes), ignoreLowBytes, sourcePort, targetPort);
} else {
if (!rulePart.matches(".+:.*(:.*)?")) {
throw new IllegalArgumentException("Invalid rule: " + rule + ", should match .+:.*(:.*)?");
}
String[] parts = rulePart.split(":");
int ip = NetworkUtil.getFirstIPAddress(parts[0]);
int sourcePort = parsePort(parts[1]);
int targetPort = parts.length == 3 ? parsePort(parts[2]) : -1;
firewallRule = new FirewallRule(ip, 0, sourcePort, targetPort);
}
var actionPart = rule.split(" ")[1];
FirewallAction action = switch (actionPart) {
case "drop" -> FirewallAction.DROP;
case "pass" -> FirewallAction.ALLOW;
default -> throw new IllegalArgumentException("Unknown action: " + actionPart);
};
logger.info("Rule: {} action: {}", firewallRule, action);
return new FirewallRuleAndAction(firewallRule, action);
}
public static void main(String[] args) throws InterruptedException {
try (Firewall program = BPFProgram.load(Firewall.class)) {
for (String rule : args) {
var ruleAndAction = parseRule(rule);
program.firewallRules.put(ruleAndAction.rule, ruleAndAction.action);
}
program.xdpAttach();
program.blockedConnections.setCallback((info) -> {
logger.info("Blocked packet from {} port {} to port {}",
NetworkUtil.intToIpAddress(info.connection.ip).getHostAddress(),
info.connection.sourcePort, info.connection.destPort);
});
while (true) {
program.consumeAndThrow();
Thread.sleep(500);
}
}
}
}