package instancectl import ( "encoding/binary" "net" "testing" ) func TestPlan14BoundConnectFilter(t *testing.T) { for _, test := range []struct { ip string ipv6, allow bool }{ {"127.0.0.1", false, false}, {"127.0.0.53", false, false}, {"127.23.4.5", false, false}, {"1.1.1.1", false, true}, {"::1", true, false}, {"::ffff:127.0.0.1", true, false}, {"2001:4860:4860::8888", true, true}, {"::ffff:1.1.1.1", true, true}, } { t.Run(test.ip, func(t *testing.T) { var ctx [24]byte ip := net.ParseIP(test.ip) if test.ipv6 { copy(ctx[8:], ip.To16()) } else { copy(ctx[4:], ip.To4()) } p := claimConnectFilter(test.ipv6) var reg uint32 for pc, steps := 0, 0; ; pc, steps = pc+1, steps+1 { if pc < 0 || pc >= len(p) || steps > 100 { t.Fatal("invalid program control flow", pc) } i := p[pc] switch i.Code { case 0x61: reg = binary.NativeEndian.Uint32(ctx[i.Offset : i.Offset+4]) case 0xdc: var b [4]byte binary.NativeEndian.PutUint32(b[:], reg) reg = binary.BigEndian.Uint32(b[:]) case 0x54: reg &= uint32(i.Immediate) case 0x15: if reg == uint32(i.Immediate) { pc += int(i.Offset) } case 0x55: if reg != uint32(i.Immediate) { pc += int(i.Offset) } case 0xb7: reg = uint32(i.Immediate) case 0x95: if (reg == 1) != test.allow { t.Fatal("wrong network verdict", reg) } return default: t.Fatal("unknown instruction", i) } } }) } }