|
| 1 | +-- |
| 2 | +-- SPDX-FileCopyrightText: (c) 2025-2026 Ashwani Kumar Kamal <ashwanikamal.im421@gmail.com> |
| 3 | +-- SPDX-License-Identifier: MIT OR GPL-2.0-only |
| 4 | +-- |
| 5 | + |
| 6 | +local tc = require("tc") |
| 7 | +local action = require("linux.tc") |
| 8 | +local skbattr = require("skb.attr") |
| 9 | + |
| 10 | +local TC_H_MAKE = function(maj, min) return (maj << 16) | min end |
| 11 | + |
| 12 | +local client_hello = 0x01 |
| 13 | +local handshake = 0x16 |
| 14 | +local server_name = 0x0000 |
| 15 | + |
| 16 | +local session = 43 |
| 17 | +local max_extensions = 17 |
| 18 | + |
| 19 | +local policy = { |
| 20 | + ["netflix%.com"] = TC_H_MAKE(1, 20), |
| 21 | + ["zoom%.com"] = TC_H_MAKE(1, 10), |
| 22 | +} |
| 23 | + |
| 24 | +local function log(sni, priority) |
| 25 | + print(string.format("sniclassify: %s %s", sni, priority)) |
| 26 | +end |
| 27 | + |
| 28 | +local function unpacker(packet, base) |
| 29 | + local byte = function (offset) |
| 30 | + return packet:getbyte(base + offset) |
| 31 | + end |
| 32 | + |
| 33 | + local short = function (offset) |
| 34 | + local offset = base + offset |
| 35 | + return packet:getbyte(offset) << 8 | packet:getbyte(offset + 1) |
| 36 | + end |
| 37 | + |
| 38 | + local str = function (offset, length) |
| 39 | + return packet:getstring(base + offset, length) |
| 40 | + end |
| 41 | + |
| 42 | + return byte, short, str |
| 43 | +end |
| 44 | + |
| 45 | +local function offset(argument) |
| 46 | + return select(2, unpacker(argument, 0))(0) |
| 47 | +end |
| 48 | + |
| 49 | +local function sniclassify(ctx) |
| 50 | + local argument = ctx:argument() |
| 51 | + local skb = skbattr(ctx:skb()) |
| 52 | + local data = skb:data() |
| 53 | + local byte, short, str = unpacker(data, offset(argument)) |
| 54 | + |
| 55 | + if byte(0) ~= handshake or byte(5) ~= client_hello then |
| 56 | + ctx:action(action.ACT_OK) |
| 57 | + return |
| 58 | + end |
| 59 | + |
| 60 | + local cipher = (session + 1) + byte(session) |
| 61 | + local compression = cipher + 2 + short(cipher) |
| 62 | + local extension = compression + 3 + byte(compression) |
| 63 | + |
| 64 | + for _ = 1, max_extensions do |
| 65 | + local data_off = extension + 4 |
| 66 | + if short(extension) == server_name then |
| 67 | + local sni = str(data_off + 5, short(data_off + 3)) |
| 68 | + for pattern, classid in pairs(policy) do |
| 69 | + if sni:match(pattern) then |
| 70 | + log(sni, classid) |
| 71 | + skb.priority = classid |
| 72 | + break |
| 73 | + end |
| 74 | + end |
| 75 | + ctx:action(action.ACT_OK) |
| 76 | + return |
| 77 | + end |
| 78 | + extension = data_off + short(extension + 2) |
| 79 | + end |
| 80 | + |
| 81 | + ctx:action(action.ACT_OK) |
| 82 | +end |
| 83 | + |
| 84 | +tc.attach(sniclassify) |
| 85 | + |
0 commit comments