Debian Codegraph @

cbpfc.go

raw symbols SCIP
1 // Package cbpfc implements a cBPF (classic BPF) to eBPF
2 // (extended BPF, not be confused with cBPF extensions) compiler.
3 //
4 // cbpfc can compile cBPF filters to:
5 // - C, which can be compiled to eBPF with Clang
6 // - eBPF
7 //
8 // Both the C and eBPF output are intended to be accepted by the kernel verifier:
9 // - All packet loads are guarded with runtime packet length checks
10 // - RegA and RegX are zero initialized as required
11 // - Division by zero is guarded by runtime checks
12 //
13 // The generated C / eBPF is intended to be embedded into a larger C / eBPF program.
14 //
15 // Footguns / limitations:
16 // - The maximum absolute offset of a packet that can be read is 0xFFFF, any accesses
17 // past that will be treated as out of bounds cBPF packet accesses, and the filter will
18 // return 0. That includes offsets added directly to the packet pointer passed in.
19 // - If the packet pointer passed in has an offset (eg because you've skipped past the
20 // ethernet header), the maximum possible offset must be passed in via EBPFOpts or COpts.
21 package cbpfc
22
23 import (
24 "fmt"
25 "sort"
26
27 "github.com/pkg/errors"
28 "golang.org/x/net/bpf"
29 )
30
31 // maxPacketOffset is the maximum packet offset the verifier allows.
32 // https://elixir.bootlin.com/linux/v5.14.8/source/kernel/bpf/verifier.c#L3223
33 const maxPacketOffset = 0xFFFF
34
35 // Map conditionals to their inverse
36 var condToInverse = map[bpf.JumpTest]bpf.JumpTest{
37 bpf.JumpEqual: bpf.JumpNotEqual,
38 bpf.JumpNotEqual: bpf.JumpEqual,
39 bpf.JumpGreaterThan: bpf.JumpLessOrEqual,
40 bpf.JumpLessThan: bpf.JumpGreaterOrEqual,
41 bpf.JumpGreaterOrEqual: bpf.JumpLessThan,
42 bpf.JumpLessOrEqual: bpf.JumpGreaterThan,
43 bpf.JumpBitsSet: bpf.JumpBitsNotSet,
44 bpf.JumpBitsNotSet: bpf.JumpBitsSet,
45 }
46
47 // pos stores the absolute position of a cBPF instruction
48 type pos uint
49
50 // skips store cBPF jumps, which are relative
51 type skip uint
52
53 // instruction wraps a bpf instruction with it's
54 // original position
55 type instruction struct {
56 bpf.Instruction
57 id pos
58 }
59
60 func (i instruction) String() string {
61 return fmt.Sprintf("%d: %v", i.id, i.Instruction)
62 }
63
64 // block contains a linear flow on instructions:
65 // - Nothing jumps into the middle of a block
66 // - Nothing jumps out of the middle of a block
67 //
68 // A block may start or end with any instruction, as any instruction
69 // can be the target of a jump.
70 //
71 // A block also knows what blocks it jumps to. This forms a DAG of blocks.
72 type block struct {
73 // Should not be directly modified, instead copy instructions to new slice
74 insns []instruction
75
76 // Map of absolute instruction positions the last instruction
77 // of this block can jump to, to the corresponding block
78 jumps map[pos]*block
79
80 // id of the instruction that started this block
81 // Unique, but not guaranteed to match insns[0].id after blocks are modified
82 id pos
83 }
84
85 // newBlock creates a block with copy of insns
86 func newBlock(insns []instruction) *block {
87 return &block{
88 insns: insns,
89 jumps: make(map[pos]*block),
90 id: insns[0].id,
91 }
92 }
93
94 func (b *block) Label() string {
95 return fmt.Sprintf("block_%d", b.id)
96 }
97
98 func (b *block) skipToPos(s skip) pos {
99 return b.last().id + 1 + pos(s)
100 }
101
102 // Get the target block of a skip
103 func (b *block) skipToBlock(s skip) *block {
104 return b.jumps[b.skipToPos(s)]
105 }
106
107 func (b *block) last() instruction {
108 return b.insns[len(b.insns)-1]
109 }
110
111 // packetGuard is a "fake" cBPF instruction
112 // that checks packet bounds before data is read from the packet.
113 type packetGuard interface {
114 bpf.Instruction
115
116 // Extend returns a guard that is the union of the current guard and o.
117 extend(o packetGuard) packetGuard
118
119 // Restrict returns a guard that is the intersection of the current guard and o.
120 restrict(o packetGuard) packetGuard
121
122 // Adjust any instructions that are covered by this guard as required.
123 adjustInsns(insns []instruction)
124 }
125
126 // packetGuardAbsolute checks packet bounds for absolute packet loads (constant offset).
127 // We only need to track the last / greatest byte read to ensure it isn't past the packet end.
128 type packetGuardAbsolute struct {
129 // The furthest (exclusive) byte read.
130 end int32
131 }
132
133 func newPacketGuardAbsolute(off uint32, size int) packetGuardAbsolute {
134 if off > maxPacketOffset {
135 panic("can't create absolute packet guard for offset")
136 }
137
138 // Absolute offsets are limited to maxPacketOffset so this can't overflow.
139 return packetGuardAbsolute{int32(off) + int32(size)}
140 }
141
142 func (a packetGuardAbsolute) extend(o packetGuard) packetGuard {
143 n := a
144 if b := o.(packetGuardAbsolute); b.end > a.end {
145 n.end = b.end
146 }
147 return n
148 }
149
150 func (a packetGuardAbsolute) restrict(o packetGuard) packetGuard {
151 n := a
152 if b := o.(packetGuardAbsolute); b.end < a.end {
153 n.end = b.end
154 }
155 return n
156 }
157
158 // We don't need to adjust instructions for absolute guards.
159 func (a packetGuardAbsolute) adjustInsns(insns []instruction) {}
160
161 // Assemble implements the Instruction Assemble method.
162 func (p packetGuardAbsolute) Assemble() (bpf.RawInstruction, error) {
163 return bpf.RawInstruction{}, errors.Errorf("unsupported")
164 }
165
166 // packetGuardIndirect checks packet bounds for indirect packet loads (RegX + constant offset).
167 // RegX and offset are both allowed to be negative, but RegX + Offset must be >= 0 (the verifier does not allow
168 // adding negative offsets to packet pointers).
169 //
170 // This requires tracking both the first and last byte read (relative to RegX) to check:
171 // - RegX + start >= 0
172 // - RegX + end < maxPacketOffset
173 // - packet_start + RegX + end < packet_end
174 //
175 // Bounds / range information is propagated in the verifier by copying a packet pointer,
176 // adding a constant (which yields a "derived" packet pointer with the same ID), and checking it against the packet_end.
177 // Subsequent LoadIndirects that are covered by this guard need to use a packet pointer with same ID as the guard to
178 // take advantage of the bounds.
179 // Ideally we would use packet_start + RegX and let each LoadIndirect instruction add its own offset,
180 // but the verifier doesn't allow the use of packet pointers with a negative offset (even if the offset
181 // would make the read positive: https://elixir.bootlin.com/linux/v5.14.12/source/kernel/bpf/verifier.c#L3287)
182 //
183 // So instead we check:
184 // - RegX + start >= 0
185 // - RegX + start < maxPacketOffset - packetStartMaxOffset - length
186 // - packet_start + RegX + start + length < packet_end
187 //
188 // This lets us reuse packet_start + RegX + start as the packet pointer for LoadIndirect,
189 // but means we need to rewrite the offsets of LoadIndirect instructions covered by this guard to subtract length.
190 type packetGuardIndirect struct {
191 // First byte read (inclusive).
192 start int32
193 // Last byte read (exclusive).
194 // int64 to avoid overflows with INT32_MAX + size
195 end int64
196
197 // packetStartMaxOffset is the maximum offset the packet start / data is at, in bytes.
198 packetStartMaxOffset uint16
199 }
200
201 func newPacketGuardIndirect(off uint32, size int, opts compileOpts) packetGuardIndirect {
202 // cBPF offsets are uint32, but are signed in reality
203 // LoadIndirect offsets are encoded as uint32 by x/net/bpf, but are signed in reality.
204 // Unlike LoadAbsolute, restrictions only apply to RegX + Offset and not Offset alone,
205 // so we have to allow INT32_MAX / INT32_MIN offsets.
206 return packetGuardIndirect{
207 start: int32(off),
208 end: int64(int32(off)) + int64(size),
209
210 packetStartMaxOffset: opts.packetStartMaxOffset,
211 }
212 }
213
214 func (a packetGuardIndirect) extend(o packetGuard) packetGuard {
215 b := o.(packetGuardIndirect)
216
217 // A 0 guard means no guard, we shouldn't extend it to cover {0,0}
218 if a == (packetGuardIndirect{}) {
219 return b
220 }
221 if b == (packetGuardIndirect{}) {
222 return a
223 }
224
225 n := a
226
227 if b.start < a.start {
228 n.start = b.start
229 }
230 if b.end > a.end {
231 n.end = b.end
232 }
233
234 return n
235 }
236
237 func (a packetGuardIndirect) restrict(o packetGuard) packetGuard {
238 b := o.(packetGuardIndirect)
239
240 // A 0 guard means no guard, that restricts everything to no guard.
241 if a == (packetGuardIndirect{}) || b == (packetGuardIndirect{}) {
242 return packetGuardIndirect{}
243 }
244
245 n := a
246
247 if b.start > a.start {
248 n.start = b.start
249 }
250 if b.end < a.end {
251 n.end = b.end
252 }
253
254 return n
255 }
256
257 // int32(RegX) + p.start must be < to maxStartOffset().
258 // This checks that it is positive, and int32(RegX) + p.end doesn't exceed maxPacketOffset.
259 // Returns 0 (check will always be false) if there is no way for the start and end of the guard to be < maxPacketOffset.
260 func (p packetGuardIndirect) maxStartOffset() int32 {
261 m := maxPacketOffset - int64(p.packetStartMaxOffset) - (p.end - int64(p.start))
262 // If m is negative, (packetStartMaxOffset + length) exceeds maxPacketOffset, there's no way for RegX + start >= 0 and RegX + end < maxPacketOffset.
263 // Return 0 so the check fails, and we return noMatch.
264 if m < 0 {
265 return 0
266 }
267
268 // +1 as it needs to be strictly less than.
269 // This lets us return 0 above to get noMatch.
270 return int32(m) + 1
271 }
272
273 // packet_start + (int32(x) + p.start) + p.length() must be <= packet_end.
274 // This lets us reuse the (int32(x) + p.start) from the maxStartOffset() check, to keep the bounds info.
275 func (p packetGuardIndirect) length() int32 {
276 // This can overflow, but it doesn't matter as we'll already have checked maxStartOffset()
277 // and caught the overflow there.
278 return int32(p.end - int64(p.start))
279 }
280
281 // Once we've determined the guard that applies for a given set of insns,
282 // asjust the offsets so they're relative to the smallest / start of the guard.
283 func (p packetGuardIndirect) adjustInsns(insns []instruction) {
284 for i := range insns {
285 switch insn := insns[i].Instruction.(type) {
286 case bpf.LoadIndirect:
287 insns[i].Instruction = bpf.LoadIndirect{
288 Off: uint32(int32(insn.Off) - p.start),
289 Size: insn.Size,
290 }
291 }
292 }
293 }
294
295 // Assemble implements the Instruction Assemble method.
296 func (p packetGuardIndirect) Assemble() (bpf.RawInstruction, error) {
297 return bpf.RawInstruction{}, errors.Errorf("unsupported")
298 }
299
300 // checksXNotZero is a "fake" instruction
301 // that returns no match if X is 0
302 type checkXNotZero struct {
303 }
304
305 // Assemble implements the Instruction Assemble method.
306 func (c checkXNotZero) Assemble() (bpf.RawInstruction, error) {
307 return bpf.RawInstruction{}, errors.Errorf("unsupported")
308 }
309
310 type compileOpts struct {
311 // packetStartMaxOffset is the maximum offset the packet start / data is at, in bytes.
312 packetStartMaxOffset uint16
313 }
314
315 // compile compiles a cBPF program to an ordered slice of blocks, with:
316 // - Registers zero initialized as required
317 // - Required packet access guards added
318 // - JumpIf and JumpIfX instructions normalized (see normalizeJumps)
319 func compile(insns []bpf.Instruction, opts compileOpts) ([]*block, error) {
320 err := validateInstructions(insns)
321 if err != nil {
322 return nil, err
323 }
324
325 instructions := toInstructions(insns)
326
327 normalizeJumps(instructions)
328
329 // Split into blocks
330 blocks, err := splitBlocks(instructions)
331 if err != nil {
332 return nil, errors.Wrapf(err, "unable to compute blocks")
333 }
334
335 // Initialize registers
336 err = initializeMemory(blocks)
337 if err != nil {
338 return nil, err
339 }
340
341 // Check we don't divide by zero
342 err = addDivideByZeroGuards(blocks)
343 if err != nil {
344 return nil, err
345 }
346
347 rewriteLargePacketOffsets(&blocks, opts)
348
349 // Guard packet loads
350 addAbsolutePacketGuards(blocks)
351 addIndirectPacketGuards(blocks, opts)
352
353 return blocks, nil
354 }
355
356 // validateInstructions checks the instructions are valid, and we support them
357 func validateInstructions(insns []bpf.Instruction) error {
358 // Can't do anything meaningful with no instructions
359 if len(insns) == 0 {
360 return errors.New("can't compile 0 instructions")
361 }
362
363 for pc, insn := range insns {
364 // Assemble does some input validation
365 _, err := insn.Assemble()
366 if err != nil {
367 return errors.Errorf("can't assemble instruction %d: %v", pc, insn)
368 }
369
370 switch i := insn.(type) {
371 case bpf.RawInstruction:
372 return errors.Errorf("unsupported instruction %d: %v", pc, insn)
373
374 // Negative constant offsets are used for extensions (and if they're supported, x/net/bpf will parse them)
375 // and other packet addressing modes we don't support: https://elixir.bootlin.com/linux/v5.14.10/source/kernel/bpf/core.c#L65
376 case bpf.LoadAbsolute:
377 if int32(i.Off) < 0 {
378 return errors.Errorf("LoadAbsolute negative offset %v", int32(i.Off))
379 }
380 case bpf.LoadMemShift:
381 if int32(i.Off) < 0 {
382 return errors.Errorf("LoadMemShift negative offset %v", int32(i.Off))
383 }
384
385 case bpf.LoadExtension:
386 switch i.Num {
387 case bpf.ExtLen:
388 break
389 default:
390 return errors.Errorf("unsupported BPF extension %d: %v", pc, insn)
391 }
392 }
393 }
394
395 return nil
396 }
397
398 func toInstructions(insns []bpf.Instruction) []instruction {
399 instructions := make([]instruction, len(insns))
400
401 for pc, insn := range insns {
402 instructions[pc] = instruction{
403 Instruction: insn,
404 id: pos(pc),
405 }
406 }
407
408 return instructions
409 }
410
411 // normalizeJumps normalizes conditional jumps to always use skipTrue:
412 // Jumps that only use skipTrue (skipFalse == 0) are unchanged.
413 // Jumps that use both skipTrue and skipFalse are unchanged.
414 // Jumps that only use skipFalse (skipTrue == 0) are inverted to only use skipTrue.
415 func normalizeJumps(insns []instruction) {
416 for pc := range insns {
417 switch i := insns[pc].Instruction.(type) {
418 case bpf.JumpIf:
419 if !shouldInvert(i.SkipTrue, i.SkipFalse) {
420 continue
421 }
422
423 insns[pc].Instruction = bpf.JumpIf{Cond: condToInverse[i.Cond], Val: i.Val, SkipTrue: i.SkipFalse, SkipFalse: i.SkipTrue}
424
425 case bpf.JumpIfX:
426 if !shouldInvert(i.SkipTrue, i.SkipFalse) {
427 continue
428 }
429
430 insns[pc].Instruction = bpf.JumpIfX{Cond: condToInverse[i.Cond], SkipTrue: i.SkipFalse, SkipFalse: i.SkipTrue}
431 }
432 }
433 }
434
435 // Check if a conditional jump should be inverted
436 func shouldInvert(skipTrue, skipFalse uint8) bool {
437 return skipTrue == 0 && skipFalse != 0
438 }
439
440 // Traverse instructions until end of first block. Target is absolute start of block.
441 // Return block-relative jump targets
442 func visitBlock(insns []instruction, target pos) (*block, []skip) {
443 for pc, insn := range insns {
444 // Relative jumps from this instruction
445 var skips []skip
446
447 switch i := insn.Instruction.(type) {
448 case bpf.Jump:
449 skips = []skip{skip(i.Skip)}
450 case bpf.JumpIf:
451 skips = []skip{skip(i.SkipTrue), skip(i.SkipFalse)}
452 case bpf.JumpIfX:
453 skips = []skip{skip(i.SkipTrue), skip(i.SkipFalse)}
454
455 case bpf.RetA, bpf.RetConstant:
456 // No extra targets to visit
457
458 default:
459 // Regular instruction, next please!
460 continue
461 }
462
463 // every insn including this one
464 return newBlock(insns[:pc+1]), skips
465 }
466
467 // Try to fall through to next block
468 return newBlock(insns), []skip{0}
469 }
470
471 // splitBlocks splits the cBPF into an ordered list of blocks.
472 //
473 // The blocks are preserved in the order they are found as this guarantees that
474 // a block only targets later blocks (cBPF jumps are positive, relative offsets).
475 // This also mimics the layout of the original cBPF, which is good for debugging.
476 func splitBlocks(instructions []instruction) ([]*block, error) {
477 // Blocks we've visited already
478 blocks := []*block{}
479
480 // map of targets to blocks that target them
481 // target 0 is for the base case
482 targets := map[pos][]*block{
483 0: nil,
484 }
485
486 // As long as we have un visited targets
487 for len(targets) > 0 {
488 sortedTargets := sortTargets(targets)
489
490 // Get the first one (not really breadth first, but close enough!)
491 target := sortedTargets[0]
492
493 end := len(instructions)
494 // If there's a next target, ensure we stop before it
495 if len(sortedTargets) > 1 {
496 end = int(sortedTargets[1])
497 }
498
499 next, nextSkips := visitBlock(instructions[target:end], target)
500
501 // Add skips to our list of things to visit
502 for _, s := range nextSkips {
503 // Convert relative skip to absolute pos
504 t := next.skipToPos(s)
505
506 if t >= pos(len(instructions)) {
507 return nil, errors.Errorf("instruction %v flows past last instruction", next.last())
508 }
509
510 targets[t] = append(targets[t], next)
511 }
512
513 jmpBlocks := targets[target]
514
515 // Mark all the blocks that jump to the block we've just visited as doing so
516 for _, jmpBlock := range jmpBlocks {
517 jmpBlock.jumps[target] = next
518 }
519
520 blocks = append(blocks, next)
521
522 // Target is now a block!
523 delete(targets, target)
524 }
525
526 return blocks, nil
527 }
528
529 // sortTargets sorts the target positions (keys), lowest first
530 func sortTargets(targets map[pos][]*block) []pos {
531 keys := make([]pos, len(targets))
532
533 i := 0
534 for k := range targets {
535 keys[i] = k
536 i++
537 }
538
539 sort.Slice(keys, func(i, j int) bool {
540 return keys[i] < keys[j]
541 })
542
543 return keys
544 }
545
546 // addDivideByZeroGuards adds runtime guards / checks to ensure
547 // the program returns no match when it would otherwise divide by zero.
548 func addDivideByZeroGuards(blocks []*block) error {
549 isDivision := func(op bpf.ALUOp) bool {
550 return op == bpf.ALUOpDiv || op == bpf.ALUOpMod
551 }
552
553 // Is RegX known to be none 0 at the start of each block
554 // We can't divide by RegA, only need to check RegX.
555 xNotZero := make(map[*block]bool)
556
557 for _, block := range blocks {
558 notZero := xNotZero[block]
559
560 // newInsns to replace those in the block
561 newInsns := []instruction{}
562 for _, insn := range block.insns {
563 switch i := insn.Instruction.(type) {
564 case bpf.ALUOpConstant:
565 if isDivision(i.Op) && i.Val == 0 {
566 return errors.Errorf("instruction %v divides by 0", insn)
567 }
568 case bpf.ALUOpX:
569 if isDivision(i.Op) && !notZero {
570 newInsns = append(newInsns, instruction{Instruction: checkXNotZero{}})
571 notZero = true
572 }
573 }
574
575 newInsns = append(newInsns, insn)
576
577 // check if X clobbered - check is invalidated
578 if memWrites(insn.Instruction).regs[bpf.RegX] {
579 notZero = false
580 }
581 }
582 block.insns = newInsns
583
584 // update the status of every block this one jumps to
585 for _, target := range block.jumps {
586 targetNotZero, ok := xNotZero[target]
587 if !ok {
588 xNotZero[target] = notZero
589 continue
590 }
591
592 // x needs to be not zero from every possible path
593 xNotZero[target] = targetNotZero && notZero
594 }
595 }
596
597 return nil
598 }
599
600 // rewriteLargePacketOffsets replaces packet loads that have constant offsets
601 // greater than the verifier allows with return 0 (no match) to mimick
602 // what the kernel does for cBPF.
603 // While cBPF allows bigger offsets, in practice they cannot match a packet.
604 // This doesn't work for LoadIndirect as the actual offset is LoadIndirect.Off + RegX,
605 // we instead rely on runtime checks (see packetGuardIndirect).
606 func rewriteLargePacketOffsets(blocks *[]*block, opts compileOpts) {
607 // All blocks are reachable when we start.
608 // But some blocks can become unreachable once we've rewritten load instructions to returns.
609 // The verifier rejects unreachable instructions, track how many other blocks go to a given block
610 // so we can remove newly unreachable blocks.
611 blockRefs := make(map[*block]int)
612
613 var newBlocks []*block
614
615 for i, block := range *blocks {
616 // No other blocks jump into this block anymore, skip it.
617 if i != 0 && blockRefs[block] == 0 {
618 continue
619 }
620 newBlocks = append(newBlocks, block)
621
622 for _, insn := range block.insns {
623 var (
624 offset uint64
625 size uint64
626 )
627
628 // LoadIndirect is handled by runtime checks as only RegX + offset is subject to maxPacketOffset.
629 switch i := insn.Instruction.(type) {
630 case bpf.LoadAbsolute:
631 offset = uint64(i.Off)
632 size = uint64(i.Size)
633 case bpf.LoadMemShift:
634 offset = uint64(i.Off)
635 size = 1
636 default:
637 continue
638 }
639
640 // A packetGuard will have to add size to the packet pointer, so it counts towards the limit.
641 if offset+size+uint64(opts.packetStartMaxOffset) > maxPacketOffset {
642 // Mimick an out of bounds load in cBPF, returning 0 / no match.
643 // The block now unconditionally returns, the other instructions in it don't matter.
644 block.insns = []instruction{
645 {Instruction: bpf.RetConstant{Val: 0}},
646 }
647
648 // This block doesn't jump to any others anymore.
649 block.jumps = nil
650
651 break
652 }
653 }
654
655 // cBPF can't jump backwards, so we can build this up as we go.
656 for _, target := range block.jumps {
657 blockRefs[target]++
658 }
659 }
660
661 *blocks = newBlocks
662 }
663
664 // addAbsolutePacketGuard adds required packet guards for absolute packet accesses to blocks.
665 func addAbsolutePacketGuards(blocks []*block) {
666 addPacketGuards(blocks, packetGuardOpts{
667 requiredGuard: func(insns []instruction) requiredGuard {
668 var biggestGuard packetGuard = packetGuardAbsolute{}
669
670 for _, insn := range insns {
671 switch i := insn.Instruction.(type) {
672 case bpf.LoadAbsolute:
673 biggestGuard = biggestGuard.extend(newPacketGuardAbsolute(i.Off, i.Size))
674 case bpf.LoadMemShift:
675 biggestGuard = biggestGuard.extend(newPacketGuardAbsolute(i.Off, 1))
676 }
677 }
678
679 // Guard covers all instructions.
680 return requiredGuard{
681 guard: biggestGuard,
682 alwaysValid: true,
683 }
684 },
685
686 zeroGuard: func() packetGuard {
687 return packetGuardAbsolute{}
688 },
689 })
690 }
691
692 // addIndirectPacketGuard adds required packet guards for indirect packet accesses to blocks.
693 func addIndirectPacketGuards(blocks []*block, opts compileOpts) {
694 addPacketGuards(blocks, packetGuardOpts{
695 requiredGuard: func(insns []instruction) requiredGuard {
696 var (
697 insnCount int
698 biggestGuard packetGuard = packetGuardIndirect{}
699 )
700
701 for _, insn := range insns {
702 insnCount++
703
704 switch i := insn.Instruction.(type) {
705 case bpf.LoadIndirect:
706 biggestGuard = biggestGuard.extend(newPacketGuardIndirect(i.Off, i.Size, opts))
707 }
708
709 // Check if we clobbered x - this invalidates the guard
710 if memWrites(insn.Instruction).regs[bpf.RegX] {
711 return requiredGuard{
712 guard: biggestGuard,
713 validForInsns: insnCount,
714 }
715 }
716 }
717
718 return requiredGuard{
719 guard: biggestGuard,
720 alwaysValid: true,
721 }
722 },
723
724 zeroGuard: func() packetGuard {
725 return packetGuardIndirect{}
726 },
727 })
728 }
729
730 type packetGuardOpts struct {
731 // requiredGuard returns the packetGuard needed by insns, and what insns it is valid for.
732 requiredGuard func(insns []instruction) requiredGuard
733
734 // zeroGuard returns an empty guard of the right type.
735 zeroGuard func() packetGuard
736 }
737
738 type requiredGuard struct {
739 guard packetGuard
740
741 // The guard covers all the requested instructions,
742 // and is still valid afterwards.
743 alwaysValid bool
744
745 // The guard covers n instructions,
746 // and isn't valid for the subsequent n+1: instructions (eg RegX was clobbered for indirect guards).
747 validForInsns int
748 }
749
750 // addPacketGuards adds packet guards as required.
751 //
752 // Traversing the DAG of blocks (by visiting the blocks a block jumps to),
753 // we know all packet guards that exist at the start of a given block.
754 // We can check if the block requires a longer / bigger guard than
755 // the shortest / least existing guard.
756 func addPacketGuards(blocks []*block, opts packetGuardOpts) {
757 // Guards in effect at the start of each block
758 // Can't jump backwards so we only need to traverse blocks once
759 guards := make(map[*block][]packetGuard)
760
761 for _, block := range blocks {
762 blockGuard := addBlockGuards(block, leastGuard(opts.zeroGuard(), guards[block]), opts)
763
764 for _, target := range block.jumps {
765 guards[target] = append(guards[target], blockGuard)
766 }
767 }
768 }
769
770 // addBlockGuards add the guards required for the instructions in block.
771 func addBlockGuards(block *block, currentGuard packetGuard, opts packetGuardOpts) packetGuard {
772 insns := block.insns
773 block.insns = nil
774
775 for len(insns) != 0 {
776 required := opts.requiredGuard(insns)
777
778 // Need a bigger guard for these insns. Don't use the bigger guard on it's own,
779 // extend the current one so we keep as much information as we have.
780 if newGuard := currentGuard.extend(required.guard); newGuard != currentGuard {
781 currentGuard = newGuard
782
783 // Last guard we need for this block -> what our children / target blocks will start with
784 if required.alwaysValid {
785 // If packets must go through a bigger guard (guaranteed guard) to match, we can use the guaranteed guard here,
786 // without changing the return value of the program:
787 // - packets smaller than the guaranteed guard cannot match anyways, we can safely reject them earlier
788 // - packets bigger than the guaranteed guard won't be affected by it
789 currentGuard = currentGuard.extend(guaranteedGuard(block.jumps, opts))
790 }
791
792 block.insns = append(block.insns, instruction{Instruction: currentGuard})
793 }
794
795 coveredInsns := insns
796 if !required.alwaysValid {
797 coveredInsns = insns[:required.validForInsns]
798 }
799
800 currentGuard.adjustInsns(coveredInsns)
801 block.insns = append(block.insns, coveredInsns...)
802
803 if required.alwaysValid {
804 // Guard covers remainder of block, and is still valid at the end.
805 return currentGuard
806 } else {
807 // Guard isn't valid anymore.
808 currentGuard = opts.zeroGuard()
809 insns = insns[required.validForInsns:]
810 }
811 }
812
813 return currentGuard
814 }
815
816 // guaranteedGuard performs a recursive depth first search of blocks in target to determine
817 // the greatest packet guard that must be made for a packet to match
818 //
819 // If the DAG of blocks needs these packet guards:
820 //
821 // [4]
822 // / \
823 // false [6]
824 // / \
825 // true [8]
826 // / \
827 // false true
828 //
829 // A packet can only match ("true") by going through guards 4 and 6. It does not have to go through guard 8.
830 // guaranteedGuard would return 6.
831 func guaranteedGuard(targets map[pos]*block, opts packetGuardOpts) packetGuard {
832
833 // Inner implementation - Uses memoization
834 return guaranteedGuardCached(targets, opts, make(map[*block]packetGuard))
835 }
836
837 // 'cache' is used in order to not calculate guard more than once for the same block.
838 func guaranteedGuardCached(targets map[pos]*block, opts packetGuardOpts, cache map[*block]packetGuard) packetGuard {
839 targetGuards := []packetGuard{}
840
841 for _, target := range targets {
842 // Block can't match the packet, ignore it
843 if blockNeverMatches(target) {
844 continue
845 }
846 if guard, ok := cache[target]; ok {
847 targetGuards = append(targetGuards, guard)
848 continue
849 }
850
851 required := opts.requiredGuard(target.insns)
852
853 // Guard invalidated by block, stop exploring
854 if !required.alwaysValid {
855 targetGuards = append(targetGuards, required.guard)
856 continue
857 }
858
859 guard := required.guard.extend(guaranteedGuardCached(target.jumps, opts, cache))
860
861 cache[target] = guard
862 targetGuards = append(targetGuards, guard)
863 }
864
865 return leastGuard(opts.zeroGuard(), targetGuards)
866 }
867
868 // leastGuard returns the smallest guard from guards.
869 // zero if there are no guards.
870 func leastGuard(zero packetGuard, guards []packetGuard) packetGuard {
871 least := zero
872
873 for i, guard := range guards {
874 if i == 0 {
875 least = guard
876 } else {
877 least = least.restrict(guard)
878 }
879 }
880
881 return least
882 }
883
884 // blockNeverMatches returns true IFF the insns in block will never match the input packet
885 func blockNeverMatches(block *block) bool {
886 for _, insn := range block.insns {
887 switch i := insn.Instruction.(type) {
888 case bpf.RetConstant:
889 if i.Val == 0 {
890 return true
891 }
892 }
893 }
894
895 return false
896 }
897
898 // memStatus represents a context defined status of registers & scratch
899 type memStatus struct {
900 // indexed by bpf.Register
901 regs [2]bool
902 scratch [16]bool
903 }
904
905 // merge merges this status with the other by applying policy to regs and scratch
906 func (r memStatus) merge(other memStatus, policy func(this, other bool) bool) memStatus {
907 newStatus := memStatus{}
908
909 for i := range newStatus.regs {
910 newStatus.regs[i] = policy(r.regs[i], other.regs[i])
911 }
912
913 for i := range newStatus.scratch {
914 newStatus.scratch[i] = policy(r.scratch[i], other.scratch[i])
915 }
916
917 return newStatus
918 }
919
920 // and merges this status with the other by logical AND
921 func (r memStatus) and(other memStatus) memStatus {
922 return r.merge(other, func(this, other bool) bool {
923 return this && other
924 })
925 }
926
927 // and merges this status with the other by logical OR
928 func (r memStatus) or(other memStatus) memStatus {
929 return r.merge(other, func(this, other bool) bool {
930 return this || other
931 })
932 }
933
934 // initializeMemory zero initializes all the registers that the BPF program reads from before writing to. Returns an error if any scratch memory is used uninitialized.
935 func initializeMemory(blocks []*block) error {
936 // memory initialized at the start of each block
937 statuses := make(map[*block]memStatus)
938
939 // uninitialized memory used so far
940 uninitialized := memStatus{}
941
942 for _, block := range blocks {
943 status := statuses[block]
944
945 for _, insn := range block.insns {
946 insnUninitialized := memUninitializedReads(insn.Instruction, status)
947 // Check no uninitialized scratch registers are read
948 for scratch, uninit := range insnUninitialized.scratch {
949 if uninit {
950 return errors.Errorf("instruction %v reads potentially uninitialized scratch register M[%d]", insn, scratch)
951 }
952 }
953
954 uninitialized = uninitialized.or(insnUninitialized)
955 status = status.or(memWrites(insn.Instruction))
956 }
957
958 // update the status of every block this one jumps to
959 for _, target := range block.jumps {
960 targetStatus, ok := statuses[target]
961 if !ok {
962 statuses[target] = status
963 continue
964 }
965
966 // memory needs to be initialized from every possible path
967 statuses[target] = targetStatus.and(status)
968 }
969 }
970
971 // new instructions we need to prepend to initialize uninitialized registers
972 initInsns := []instruction{}
973 for reg, uninit := range uninitialized.regs {
974 if !uninit {
975 continue
976 }
977
978 initInsns = append(initInsns, instruction{
979 Instruction: bpf.LoadConstant{
980 Dst: bpf.Register(reg),
981 Val: 0,
982 },
983 })
984 }
985 blocks[0].insns = append(initInsns, blocks[0].insns...)
986 return nil
987 }
988
989 // memUninitializedReads returns the memory read by insn that has not yet been initialized according to initialized.
990 func memUninitializedReads(insn bpf.Instruction, initialized memStatus) memStatus {
991 return memReads(insn).merge(initialized, func(read, init bool) bool {
992 return read && !init
993 })
994 }
995
996 // memReads returns the memory read by insn
997 func memReads(insn bpf.Instruction) memStatus {
998 read := memStatus{}
999
1000 switch i := insn.(type) {
1001 case bpf.ALUOpConstant:
1002 read.regs[bpf.RegA] = true
1003 case bpf.ALUOpX:
1004 read.regs[bpf.RegA] = true
1005 read.regs[bpf.RegX] = true
1006
1007 case bpf.JumpIf:
1008 read.regs[bpf.RegA] = true
1009 case bpf.JumpIfX:
1010 read.regs[bpf.RegA] = true
1011 read.regs[bpf.RegX] = true
1012
1013 case bpf.LoadIndirect:
1014 read.regs[bpf.RegX] = true
1015 case bpf.LoadScratch:
1016 read.scratch[i.N] = true
1017
1018 case bpf.NegateA:
1019 read.regs[bpf.RegA] = true
1020
1021 case bpf.RetA:
1022 read.regs[bpf.RegA] = true
1023
1024 case bpf.StoreScratch:
1025 read.regs[i.Src] = true
1026
1027 case bpf.TAX:
1028 read.regs[bpf.RegA] = true
1029 case bpf.TXA:
1030 read.regs[bpf.RegX] = true
1031 }
1032
1033 return read
1034 }
1035
1036 // memWrites returns the memory written by insn
1037 func memWrites(insn bpf.Instruction) memStatus {
1038 write := memStatus{}
1039
1040 switch i := insn.(type) {
1041 case bpf.ALUOpConstant:
1042 write.regs[bpf.RegA] = true
1043 case bpf.ALUOpX:
1044 write.regs[bpf.RegA] = true
1045
1046 case bpf.LoadAbsolute:
1047 write.regs[bpf.RegA] = true
1048 case bpf.LoadConstant:
1049 write.regs[i.Dst] = true
1050 case bpf.LoadExtension:
1051 write.regs[bpf.RegA] = true
1052 case bpf.LoadIndirect:
1053 write.regs[bpf.RegA] = true
1054 case bpf.LoadMemShift:
1055 write.regs[bpf.RegX] = true
1056 case bpf.LoadScratch:
1057 write.regs[i.Dst] = true
1058
1059 case bpf.NegateA:
1060 write.regs[bpf.RegA] = true
1061
1062 case bpf.StoreScratch:
1063 write.scratch[i.N] = true
1064
1065 case bpf.TAX:
1066 write.regs[bpf.RegX] = true
1067 case bpf.TXA:
1068 write.regs[bpf.RegA] = true
1069 }
1070
1071 return write
1072 }