Debian Codegraph @

example_sock_extract_dist_test.go

raw symbols SCIP
1 //go:build linux
2
3 package ebpf_test
4
5 // This code is derived from https://github.com/cloudflare/cloudflare-blog/tree/master/2018-03-ebpf
6 //
7 // Copyright (c) 2015-2017 Cloudflare, Inc. All rights reserved.
8 //
9 // Redistribution and use in source and binary forms, with or without
10 // modification, are permitted provided that the following conditions are
11 // met:
12 //
13 // * Redistributions of source code must retain the above copyright
14 // notice, this list of conditions and the following disclaimer.
15 // * Redistributions in binary form must reproduce the above
16 // copyright notice, this list of conditions and the following disclaimer
17 // in the documentation and/or other materials provided with the
18 // distribution.
19 // * Neither the name of the Cloudflare, Inc. nor the names of its
20 // contributors may be used to endorse or promote products derived from
21 // this software without specific prior written permission.
22 //
23 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
26 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
27 // HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
28 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
29 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
30 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
31 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
32 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
33 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34
35 import (
36 "fmt"
37 "net"
38 "syscall"
39
40 "github.com/cilium/ebpf"
41 "github.com/cilium/ebpf/asm"
42 )
43
44 // ExampleExtractDistance shows how to attach an eBPF socket filter to
45 // extract the network distance of an IP host.
46 func Example_extractDistance() {
47 filter, TTLs, err := newDistanceFilter()
48 if err != nil {
49 panic(err)
50 }
51 defer filter.Close()
52 defer TTLs.Close()
53
54 // Attach filter before the call to connect()
55 dialer := net.Dialer{
56 Control: func(network, address string, c syscall.RawConn) (err error) {
57 const SO_ATTACH_BPF = 50
58
59 err = c.Control(func(fd uintptr) {
60 err = syscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, SO_ATTACH_BPF, filter.FD())
61 })
62 return err
63 },
64 }
65
66 conn, err := dialer.Dial("tcp", "1.1.1.1:53")
67 if err != nil {
68 panic(err)
69 }
70 conn.Close()
71
72 minDist, err := minDistance(TTLs)
73 if err != nil {
74 panic(err)
75 }
76
77 fmt.Println("1.1.1.1:53 is", minDist, "hops away")
78 }
79
80 func newDistanceFilter() (*ebpf.Program, *ebpf.Map, error) {
81 const ETH_P_IPV6 uint16 = 0x86DD
82
83 ttls, err := ebpf.NewMap(&ebpf.MapSpec{
84 Type: ebpf.Hash,
85 KeySize: 4,
86 ValueSize: 8,
87 MaxEntries: 4,
88 })
89 if err != nil {
90 return nil, nil, err
91 }
92
93 insns := asm.Instructions{
94 // r1 has ctx
95 // r0 = ctx[16] (aka protocol)
96 asm.LoadMem(asm.R0, asm.R1, 16, asm.Word),
97
98 // Perhaps ipv6
99 asm.LoadImm(asm.R2, int64(ETH_P_IPV6), asm.DWord),
100 asm.HostTo(asm.BE, asm.R2, asm.Half),
101 asm.JEq.Reg(asm.R0, asm.R2, "ipv6"),
102
103 // otherwise assume ipv4
104 // 8th byte in IPv4 is TTL
105 // LDABS requires ctx in R6
106 asm.Mov.Reg(asm.R6, asm.R1),
107 asm.LoadAbs(-0x100000+8, asm.Byte),
108 asm.Ja.Label("store-ttl"),
109
110 // 7th byte in IPv6 is Hop count
111 // LDABS requires ctx in R6
112 asm.Mov.Reg(asm.R6, asm.R1).WithSymbol("ipv6"),
113 asm.LoadAbs(-0x100000+7, asm.Byte),
114
115 // stash the load result into FP[-4]
116 asm.StoreMem(asm.RFP, -4, asm.R0, asm.Word).WithSymbol("store-ttl"),
117 // stash the &FP[-4] into r2
118 asm.Mov.Reg(asm.R2, asm.RFP),
119 asm.Add.Imm(asm.R2, -4),
120
121 // r1 must point to map
122 asm.LoadMapPtr(asm.R1, ttls.FD()),
123 asm.FnMapLookupElem.Call(),
124
125 // load ok? inc. Otherwise? jmp to mapupdate
126 asm.JEq.Imm(asm.R0, 0, "update-map"),
127 asm.Mov.Imm(asm.R1, 1),
128 asm.StoreXAdd(asm.R0, asm.R1, asm.DWord),
129 asm.Ja.Label("exit"),
130
131 // MapUpdate
132 // r1 has map ptr
133 asm.LoadMapPtr(asm.R1, ttls.FD()).WithSymbol("update-map"),
134 // r2 has key -> &FP[-4]
135 asm.Mov.Reg(asm.R2, asm.RFP),
136 asm.Add.Imm(asm.R2, -4),
137 // r3 has value -> &FP[-16] , aka 1
138 asm.StoreImm(asm.RFP, -16, 1, asm.DWord),
139 asm.Mov.Reg(asm.R3, asm.RFP),
140 asm.Add.Imm(asm.R3, -16),
141 // r4 has flags, 0
142 asm.Mov.Imm(asm.R4, 0),
143 asm.FnMapUpdateElem.Call(),
144
145 // set exit code to -1, don't trunc packet
146 asm.Mov.Imm(asm.R0, -1).WithSymbol("exit"),
147 asm.Return(),
148 }
149
150 prog, err := ebpf.NewProgram(&ebpf.ProgramSpec{
151 Name: "distance_filter",
152 Type: ebpf.SocketFilter,
153 License: "GPL",
154 Instructions: insns,
155 })
156 if err != nil {
157 ttls.Close()
158 return nil, nil, err
159 }
160
161 return prog, ttls, nil
162 }
163
164 func minDistance(TTLs *ebpf.Map) (int, error) {
165 var (
166 entries = TTLs.Iterate()
167 ttl uint32
168 minDist uint32 = 255
169 count uint64
170 )
171 for entries.Next(&ttl, &count) {
172 var dist uint32
173 switch {
174 case ttl > 128:
175 dist = 255 - ttl
176 case ttl > 64:
177 dist = 128 - ttl
178 case ttl > 32:
179 dist = 64 - ttl
180 default:
181 dist = 32 - ttl
182 }
183 if minDist > dist {
184 minDist = dist
185 }
186 }
187 return int(minDist), entries.Err()
188 }