Created
March 29, 2022 21:27
-
-
Save icamys/429c6bda48498151cf3ac56768c15186 to your computer and use it in GitHub Desktop.
BPF builder
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
) | |
type BPFFilter string | |
func (f *BPFFilter) AndExpr(expr string) { | |
if len(*f) > 0 { | |
*f = BPFFilter(fmt.Sprintf("(%s) and %s", *f, expr)) | |
} else { | |
*f = BPFFilter(expr) | |
} | |
} | |
func (f *BPFFilter) OrExpr(expr string) { | |
if len(*f) > 0 { | |
*f = BPFFilter(fmt.Sprintf("(%s) or %s", *f, expr)) | |
} else { | |
*f = BPFFilter(expr) | |
} | |
} | |
func (f *BPFFilter) String() string { | |
return string(*f) | |
} | |
// buildBPFFilter builds a BPF filter for the sniffer | |
// syntax: https://biot.com/capstats/bpf.html | |
func buildBPFFilter(portRange *roaring.Bitmap) BPFFilter { | |
var filter BPFFilter | |
var port uint32 = 0 | |
var prevPort uint32 = 0 | |
var rangeStart uint32 = 0 | |
var rangeEnd uint32 = 0 | |
var it = portRange.Iterator() | |
for it.HasNext() { | |
port = it.Next() // 2 | |
if rangeStart == 0 { | |
rangeStart = port | |
} | |
if prevPort != 0 && port-prevPort != 1 { | |
rangeEnd = prevPort | |
if rangeStart == rangeEnd { | |
filter.OrExpr(fmt.Sprintf("dst port %d", rangeStart)) | |
} else { | |
filter.OrExpr(fmt.Sprintf("dst portrange %d-%d", rangeStart, rangeEnd)) | |
} | |
rangeStart = port | |
} | |
prevPort = port | |
} | |
rangeEnd = port | |
if rangeStart == rangeEnd { | |
filter.OrExpr(fmt.Sprintf("dst port %d", rangeStart)) | |
} else { | |
filter.OrExpr(fmt.Sprintf("dst portrange %d-%d", rangeStart, rangeEnd)) | |
} | |
filter.OrExpr("icmp or icmp6 or igmp or igrp or pim or ah or esp or vrrp") | |
return filter | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment