forked from cilium/cilium
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bpf.go
267 lines (220 loc) · 7.22 KB
/
bpf.go
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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
// Copyright 2016-2017 Authors of Cilium
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package endpoint
import (
"bufio"
"encoding/binary"
"fmt"
"os"
"os/exec"
"path"
"path/filepath"
"strconv"
"github.com/cilium/cilium/bpf/ctmap"
"github.com/cilium/cilium/bpf/geneve"
"github.com/cilium/cilium/bpf/policymap"
"github.com/cilium/cilium/common"
"github.com/cilium/cilium/pkg/policy"
"github.com/cilium/cilium/pkg/u8proto"
)
const (
ProxyMaxElements = 1024
)
func (e *Endpoint) writeL4Map(fw *bufio.Writer, owner Owner, m policy.L4PolicyMap, config string) error {
array := ""
for _, l4 := range m {
// Represents struct l4_allow in bpf/lib/l4.h
protoNum, err := u8proto.ParseProtocol(l4.Protocol)
if err != nil {
return fmt.Errorf("invalid protocol %s", l4.Protocol)
}
dport := common.Swab16(uint16(l4.Port))
redirect := uint16(0)
redirect = common.Swab16(redirect)
entry := fmt.Sprintf("{%d,%d,%d}", dport, redirect, protoNum)
if array != "" {
array = array + "," + entry
} else {
array = entry
}
}
if array == "" {
fmt.Fprintf(fw, "#undef %s\n", config)
} else {
fmt.Fprintf(fw, "#define %s {%s}\n", config, array)
}
return nil
}
func (e *Endpoint) writeL4Policy(fw *bufio.Writer, owner Owner) error {
if e.Consumable == nil || e.Consumable.L4Policy == nil {
return nil
}
policy := e.Consumable.L4Policy
if err := e.writeL4Map(fw, owner, policy.Ingress, "CFG_L4_INGRESS"); err != nil {
return err
}
if err := e.writeL4Map(fw, owner, policy.Egress, "CFG_L4_EGRESS"); err != nil {
return err
}
return nil
}
func (e *Endpoint) writeHeaderfile(prefix string, owner Owner) error {
headerPath := filepath.Join(prefix, common.CHeaderFileName)
f, err := os.Create(headerPath)
if err != nil {
return fmt.Errorf("failed to open file %s for writing: %s", headerPath, err)
}
defer f.Close()
fw := bufio.NewWriter(f)
fmt.Fprint(fw, "/*\n")
if epStr64, err := e.Base64(); err == nil {
fmt.Fprintf(fw, " * %s%s:%s\n * \n", common.CiliumCHeaderPrefix,
common.Version, epStr64)
} else {
e.LogStatus(Warning, fmt.Sprintf("Unable to create a base64: %s", err))
}
if e.DockerID == "" {
fmt.Fprintf(fw, " * Docker Network ID: %s\n", e.DockerNetworkID)
fmt.Fprintf(fw, " * Docker Endpoint ID: %s\n", e.DockerEndpointID)
} else {
fmt.Fprintf(fw, " * Docker Container ID: %s\n", e.DockerID)
}
fmt.Fprintf(fw, ""+
" * MAC: %s\n"+
" * IPv6 address: %s\n"+
" * IPv4 address: %s\n"+
" * Identity: %d\n"+
" * PolicyMap: %s\n"+
" * NodeMAC: %s\n"+
" */\n\n",
e.LXCMAC, e.IPv6.String(), e.IPv4.String(),
e.SecLabel.ID, path.Base(e.PolicyMapPath()),
e.NodeMAC)
fw.WriteString("/*\n")
fw.WriteString(" * Labels:\n")
if len(e.SecLabel.Labels) == 0 {
fmt.Fprintf(fw, " * - %s\n", "(no labels)")
} else {
for _, v := range e.SecLabel.Labels {
fmt.Fprintf(fw, " * - %s\n", v)
}
}
fw.WriteString(" */\n\n")
fw.WriteString(common.FmtDefineAddress("LXC_MAC", e.LXCMAC))
fw.WriteString(common.FmtDefineAddress("LXC_IP", e.IPv6))
if e.IPv4 != nil {
fmt.Fprintf(fw, "#define LXC_IPV4 %#x\n", binary.BigEndian.Uint32(e.IPv4))
}
fw.WriteString(common.FmtDefineAddress("NODE_MAC", e.NodeMAC))
geneveOpts, err := writeGeneve(prefix, e)
if err != nil {
return err
} else {
fw.WriteString(common.FmtDefineArray("GENEVE_OPTS", geneveOpts))
}
fmt.Fprintf(fw, "#define LXC_ID %#x\n", e.ID)
fmt.Fprintf(fw, "#define LXC_ID_NB %#x\n", common.Swab16(e.ID))
fmt.Fprintf(fw, "#define SECLABEL %s\n", e.SecLabel.ID.StringID())
fmt.Fprintf(fw, "#define SECLABEL_NB %#x\n", common.Swab32(e.SecLabel.ID.Uint32()))
fmt.Fprintf(fw, "#define POLICY_MAP %s\n", path.Base(e.PolicyMapPath()))
fmt.Fprintf(fw, "#define CT_MAP_SIZE 64000\n")
fmt.Fprintf(fw, "#define CT_MAP6 %s\n", ctmap.MapName6+strconv.Itoa(int(e.ID)))
fmt.Fprintf(fw, "#define CT_MAP4 %s\n", ctmap.MapName4+strconv.Itoa(int(e.ID)))
// Always enable L4 and L3 load balancer for now
fw.WriteString("#define LB_L3\n")
fw.WriteString("#define LB_L4\n")
// Endpoint options
fw.WriteString(e.Opts.GetFmtList())
fw.WriteString("#define LXC_PORT_MAPPINGS ")
for _, m := range e.PortMap {
// Write mappings directly in network byte order so we don't have
// to convert it in the fast path
fmt.Fprintf(fw, "{%#x,%#x},", common.Swab16(m.From), common.Swab16(m.To))
}
fw.WriteString("\n")
if err := e.writeL4Policy(fw, owner); err != nil {
return err
}
return fw.Flush()
}
// FIXME: Clean this function up
func writeGeneve(prefix string, ep *Endpoint) ([]byte, error) {
// Write container options values for each available option in
// bpf/lib/geneve.h
// GENEVE_CLASS_EXPERIMENTAL, GENEVE_TYPE_SECLABEL
err := geneve.WriteOpts(filepath.Join(prefix, "geneve_opts.cfg"), "0xffff", "0x1", "4", fmt.Sprintf("%08x", ep.SecLabel.ID.Uint32()))
if err != nil {
return nil, fmt.Errorf("Could not write geneve options %s", err)
}
_, rawData, err := geneve.ReadOpts(filepath.Join(prefix, "geneve_opts.cfg"))
if err != nil {
return nil, fmt.Errorf("Could not read geneve options %s", err)
}
return rawData, nil
}
func (e *Endpoint) runInit(owner Owner, prefix string) error {
libdir := owner.GetLibraryDir()
rundir := owner.GetRuntimeDir()
args := []string{libdir, rundir, prefix, e.IfName}
out, err := exec.Command(filepath.Join(libdir, "join_ep.sh"), args...).CombinedOutput()
if err != nil {
log.Warningf("Command execution failed: %s", err)
log.Warningf("Command output:\n%s", out)
return fmt.Errorf("error: %q command output: %q", err, out)
}
return nil
}
// regenerateBPF rewrites all headers and updates all BPF maps to reflect the
// specified endpoint.
func (e *Endpoint) regenerateBPF(owner Owner, prefix string) error {
var err error
if err = e.writeHeaderfile(prefix, owner); err != nil {
return fmt.Errorf("unable to write header file: %s", err)
}
// If dry mode is enabled, no changes to BPF maps are performed
if owner.DryModeEnabled() {
return nil
}
// Anything below this point must be reverted upon failure as we are
// changing live BPF maps
createdPolicyMap := false
defer func() {
if err != nil {
if createdPolicyMap {
// Remove policy map file only if it was created
// in this update cycle
if e.Consumable != nil {
e.Consumable.RemoveMap(e.PolicyMap)
}
os.RemoveAll(e.PolicyMapPath())
e.PolicyMap = nil
}
}
}()
if e.PolicyMap == nil {
e.PolicyMap, createdPolicyMap, err = policymap.OpenMap(e.PolicyMapPath())
if err != nil {
return err
}
}
// Only generate & populate policy map if a seclabel and consumer model is set up
if e.Consumable != nil {
e.Consumable.AddMap(e.PolicyMap)
}
if err = e.runInit(owner, prefix); err != nil {
return err
}
// The last operation hooks the endpoint into the endpoint table and exposes it
return owner.WriteEndpoint(e)
}