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
// Package bpf implements a small classic-BPF (cBPF) assembler, interpreter and
// seccomp-filter compiler used by the gonix sandbox builder.
//
// Lix delegates seccomp filter generation to libseccomp (see
// lix/libstore/platform/linux.cc compileSyscallFilter, which calls
// seccomp_export_bpf).  gonix is built with CGO_ENABLED=0 and therefore cannot
// link libseccomp, so we reproduce the relevant subset of its behaviour: an
// allowlist filter over struct seccomp_data that allows a fixed set of
// syscalls, denies the rest with ENOSYS, special-cases the setxattr family with
// ENOTSUP and the chmod family with an argument check (EPERM for setuid/setgid).
//
// This file is the lowest layer: a label-based cBPF assembler.  Higher layers
// (seccomp.go) emit symbolic instructions referencing labels; Assemble resolves
// the labels to relative jump offsets.
package bpf

import (
	"fmt"

	"golang.org/x/sys/unix"
)

// classic-BPF opcode bits.  Only the subset emitted by the seccomp compiler is
// defined here; the interpreter (interp.go) implements exactly this subset.
const (
	// instruction classes
	classLD  = 0x00
	classLDX = 0x01
	classALU = 0x04
	classJMP = 0x05
	classRET = 0x06

	// ld/ldx width + addressing modes
	sizeW   = 0x00 // 32-bit word
	modeIMM = 0x00 // A = k
	modeABS = 0x20 // A = data[k]

	// alu / jmp operand source
	srcK = 0x00 // operand is k
	srcA = 0x10 // ret: return A (vs return k)

	// alu ops
	aluAND = 0x50

	// jmp ops
	jmpJA   = 0x00 // pc += k (32-bit, unconditional)
	jmpJEQ  = 0x10 // A == k
	jmpJGE  = 0x30 // A >= k
	jmpJSET = 0x40 // A & k != 0
)

// Composite opcodes the generator and interpreter agree on.
const (
	OpLdAbsW  = classLD | sizeW | modeABS // A = seccomp_data[k]
	OpLdImmW  = classLD | sizeW | modeIMM // A = k
	OpAluAndK = classALU | aluAND | srcK  // A &= k
	OpJeqK    = classJMP | jmpJEQ | srcK  // if A == k
	OpJgeK    = classJMP | jmpJGE | srcK  // if A >= k
	OpJsetK   = classJMP | jmpJSET | srcK // if A & k != 0
	OpJa      = classJMP | jmpJA | srcK   // pc += k+1
	OpRetK    = classRET | srcK           // return k
)

// seccomp_data field byte offsets (struct seccomp_data, little-endian).
const (
	OffNr   = 0 // int nr
	OffArch = 4 // __u32 arch
	OffIP   = 8 // __u64 instruction_pointer
	// args[6] start at 16; arg n low half = 16+8n, high half = 16+8n+4.
	offArgs = 16
)

// ArgLow returns the seccomp_data offset of the low 32 bits of argument n.
func ArgLow(n int) uint32 { return uint32(offArgs + 8*n) }

// ArgHigh returns the seccomp_data offset of the high 32 bits of argument n.
func ArgHigh(n int) uint32 { return uint32(offArgs + 8*n + 4) }

// seccomp return actions (subset).  The low 16 bits of an ERRNO action carry
// the errno value.
const (
	RetKillProcess uint32 = 0x80000000
	RetErrno       uint32 = 0x00050000
	RetAllow       uint32 = 0x7fff0000
)

// Errno builds a SECCOMP_RET_ERRNO action carrying the given errno.
func Errno(e uint16) uint32 { return RetErrno | uint32(e) }

// instr is a symbolic instruction prior to label resolution.  For jumps,
// labelT/labelF name the true/false targets ("" means "fall through to the next
// instruction", i.e. offset 0).  For BPF_JA only labelT is meaningful.
type instr struct {
	op     uint16
	k      uint32
	labelT string
	labelF string
	isJump bool
	isJA   bool
}

// Program accumulates symbolic instructions and labels, then resolves them.
type Program struct {
	ins    []instr
	labels map[string]int // label name -> index into ins (the instr it precedes)
}

// NewProgram returns an empty Program.
func NewProgram() *Program {
	return &Program{labels: map[string]int{}}
}

// Label marks the current position with a name that jumps may target.  Multiple
// labels may share a position.  A label may be defined before or after the jumps
// that reference it (forward and backward references both resolve).
func (p *Program) Label(name string) {
	if _, dup := p.labels[name]; dup {
		panic(fmt.Sprintf("bpf: duplicate label %q", name))
	}
	p.labels[name] = len(p.ins)
}

// Stmt appends a non-jump instruction (LD/ALU/RET).
func (p *Program) Stmt(op uint16, k uint32) {
	p.ins = append(p.ins, instr{op: op, k: k})
}

// Ret appends a RET with the given action constant.
func (p *Program) Ret(action uint32) {
	p.ins = append(p.ins, instr{op: OpRetK, k: action})
}

// Jump appends a conditional jump (JEQ/JGE/JSET).  labelT is taken when the
// condition holds; labelF when it does not.  An empty label means "fall through"
// (relative offset 0).
func (p *Program) Jump(op uint16, k uint32, labelT, labelF string) {
	p.ins = append(p.ins, instr{op: op, k: k, labelT: labelT, labelF: labelF, isJump: true})
}

// Ja appends an unconditional long jump to a label (BPF_JA, 32-bit offset).
func (p *Program) Ja(label string) {
	p.ins = append(p.ins, instr{op: OpJa, labelT: label, isJump: true, isJA: true})
}

// Len returns the number of instructions emitted so far (useful for codegen
// that needs to know block sizes).
func (p *Program) Len() int { return len(p.ins) }

// Assemble resolves all labels into relative offsets and returns the concrete
// sock_filter program in a single pass.
//
// Conditional jumps (JEQ/JGE/JSET) encode their targets in 8-bit jt/jf fields,
// so a target more than 255 instructions away cannot be reached directly.  The
// seccomp code generator is structured so that every conditional jump targets a
// nearby instruction (its group-local RET/arg-check), and all long jumps use
// BPF_JA (a 32-bit offset).  If a conditional offset nonetheless exceeds 255 it
// is a codegen bug, reported as an error rather than silently truncated.
func (p *Program) Assemble() ([]unix.SockFilter, error) {
	out := make([]unix.SockFilter, len(p.ins))
	for i, in := range p.ins {
		f := unix.SockFilter{Code: in.op, K: in.k}
		switch {
		case in.isJA:
			off, err := resolve(p.labels, in.labelT, i)
			if err != nil {
				return nil, err
			}
			f.K = uint32(off)
		case in.isJump:
			jt, err := resolve(p.labels, in.labelT, i)
			if err != nil {
				return nil, err
			}
			jf, err := resolve(p.labels, in.labelF, i)
			if err != nil {
				return nil, err
			}
			if jt > 255 || jf > 255 {
				return nil, fmt.Errorf("bpf: conditional jump at %d exceeds 255 (jt=%d jf=%d); codegen must keep leaves local or use BPF_JA", i, jt, jf)
			}
			f.Jt = uint8(jt)
			f.Jf = uint8(jf)
		}
		out[i] = f
	}
	return out, nil
}

// resolve returns the forward distance (target - (from+1)) for a label, or an
// error if undefined or backward (cBPF allows only forward jumps).
func resolve(labels map[string]int, label string, from int) (int, error) {
	if label == "" {
		return 0, nil
	}
	target, ok := labels[label]
	if !ok {
		return 0, fmt.Errorf("bpf: undefined label %q", label)
	}
	off := target - (from + 1)
	if off < 0 {
		return 0, fmt.Errorf("bpf: backward jump to %q (cBPF only allows forward jumps)", label)
	}
	return off, nil
}

// Bytes serialises an assembled program into the raw sock_filter byte layout
// consumed by seccomp(SECCOMP_SET_MODE_FILTER) via loadSeccompFilter.
func Bytes(prog []unix.SockFilter) []byte {
	const sizeofSockFilter = 8
	b := make([]byte, len(prog)*sizeofSockFilter)
	for i, f := range prog {
		o := i * sizeofSockFilter
		// struct sock_filter { u16 code; u8 jt; u8 jf; u32 k; } little-endian.
		b[o+0] = byte(f.Code)
		b[o+1] = byte(f.Code >> 8)
		b[o+2] = f.Jt
		b[o+3] = f.Jf
		b[o+4] = byte(f.K)
		b[o+5] = byte(f.K >> 8)
		b[o+6] = byte(f.K >> 16)
		b[o+7] = byte(f.K >> 24)
	}
	return b
}