-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathbasic_match.ks
More file actions
93 lines (76 loc) · 2.77 KB
/
Copy pathbasic_match.ks
File metadata and controls
93 lines (76 loc) · 2.77 KB
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
// Basic Match Construct Demo for KernelScript
// Demonstrates packet matching with the new match construct
include "xdp.kh"
// Protocol constants
enum IpProtocol {
ICMP = 1,
TCP = 6,
UDP = 17
}
// Helper functions for packet processing (declared first)
@helper
fn get_ip_protocol(ctx: *xdp_md) -> u32 {
// In a real implementation, this would extract the protocol field
// from the IP header. For demo purposes, we return TCP.
return 6 // IPPROTO_TCP
}
@helper
fn get_tcp_dest_port(ctx: *xdp_md) -> u32 {
// In a real implementation, this would extract the destination port
// from the TCP header. For demo purposes, we return HTTP.
return 80 // HTTP port
}
@helper
fn get_udp_dest_port(ctx: *xdp_md) -> u32 {
// In a real implementation, this would extract the destination port
// from the UDP header. For demo purposes, we return DNS.
return 53 // DNS port
}
// Specialized TCP port-based classifier (tail-callable)
@xdp
fn tcp_port_classifier(ctx: *xdp_md) -> xdp_action {
var port = get_tcp_dest_port(ctx)
return match (port) {
80: XDP_PASS, // Allow HTTP
443: XDP_PASS, // Allow HTTPS
22: XDP_PASS, // Allow SSH
21: XDP_DROP, // Block FTP for security
23: XDP_DROP, // Block Telnet (insecure)
default: XDP_PASS // Allow other TCP ports by default
}
}
// Specialized UDP port-based classifier (tail-callable)
@xdp
fn udp_port_classifier(ctx: *xdp_md) -> xdp_action {
var port = get_udp_dest_port(ctx)
return match (port) {
53: XDP_PASS, // Allow DNS
123: XDP_PASS, // Allow NTP
161: XDP_DROP, // Block SNMP (security risk)
69: XDP_DROP, // Block TFTP (insecure)
default: XDP_PASS // Allow other UDP ports by default
}
}
// Main packet classifier using match construct with tail call delegation
@xdp
fn packet_classifier(ctx: *xdp_md) -> xdp_action {
var protocol = get_ip_protocol(ctx)
// Match construct provides clean protocol-based delegation
return match (protocol) {
TCP: tcp_port_classifier(ctx), // Tail call to TCP specialist
UDP: udp_port_classifier(ctx), // Tail call to UDP specialist
ICMP: XDP_DROP, // Drop ICMP for security
default: XDP_ABORTED // Abort unknown protocols
}
}
fn main() -> i32 {
var prog = load(packet_classifier)
attach(prog, "lo", 0)
print("Packet classifier attached to loopback interface")
print("Processing packets with pattern matching...")
// In a real application, the program would run here
// For demonstration, we detach after showing the lifecycle
detach(prog)
print("Packet classifier detached")
return 0
}