diff --git a/infra/conf/transport_finalmask.go b/infra/conf/transport_finalmask.go index e4c579dda117..959b80f634d2 100644 --- a/infra/conf/transport_finalmask.go +++ b/infra/conf/transport_finalmask.go @@ -20,6 +20,7 @@ import ( "github.com/xtls/xray-core/transport/internet/finalmask/mkcp/header" "github.com/xtls/xray-core/transport/internet/finalmask/mkcp/original" "github.com/xtls/xray-core/transport/internet/finalmask/noise" + "github.com/xtls/xray-core/transport/internet/finalmask/rawpacket" "github.com/xtls/xray-core/transport/internet/finalmask/realm" "github.com/xtls/xray-core/transport/internet/finalmask/salamander" "github.com/xtls/xray-core/transport/internet/finalmask/sudoku" @@ -70,6 +71,7 @@ var ( tcpmaskLoader = NewJSONConfigLoader(ConfigCreatorCache{ "header-custom": func() interface{} { return new(HeaderCustomTCP) }, "fragment": func() interface{} { return new(FragmentMask) }, + "rawpacket": func() interface{} { return new(RawpacketMask) }, "sudoku": func() interface{} { return new(Sudoku) }, "xmc": func() interface{} { return new(XMC) }, }, "type", "settings") @@ -231,6 +233,55 @@ func (c *HeaderCustomTCP) Build() (proto.Message, error) { }, nil } +type RawpacketMask struct { + Mode string `json:"mode"` + RemoteAddress string `json:"remoteAddress"` + RemotePort uint16 `json:"remotePort"` + RecvPort uint16 `json:"recvPort"` + SpoofIPs []string `json:"spoofIPs"` + Protocols []string `json:"protocols"` + MTU uint16 `json:"mtu"` + Target string `json:"target"` + TTL uint8 `json:"ttl"` + SendTransport string `json:"sendTransport"` + RecvTransport string `json:"recvTransport"` + RelayAddress string `json:"relayAddress"` + RelayPort uint16 `json:"relayPort"` + ClientIP string `json:"clientIP"` + ClientPort uint16 `json:"clientPort"` + PeerSpoofIP string `json:"peerSpoofIP"` + SpoofPort uint16 `json:"spoofPort"` + Auth string `json:"auth"` + SuppressRst bool `json:"suppressRst"` + Masquerade string `json:"masquerade"` +} + +func (c *RawpacketMask) Build() (proto.Message, error) { + config := &rawpacket.Config{ + Mode: c.Mode, + RemoteAddress: c.RemoteAddress, + RemotePort: uint32(c.RemotePort), + RecvPort: uint32(c.RecvPort), + SpoofIps: c.SpoofIPs, + Protocols: c.Protocols, + Mtu: uint32(c.MTU), + Target: c.Target, + Ttl: uint32(c.TTL), + SendTransport: c.SendTransport, + RecvTransport: c.RecvTransport, + RelayAddress: c.RelayAddress, + RelayPort: uint32(c.RelayPort), + ClientIp: c.ClientIP, + ClientPort: uint32(c.ClientPort), + PeerSpoofIp: c.PeerSpoofIP, + SpoofPort: uint32(c.SpoofPort), + Auth: c.Auth, + SuppressRst: c.SuppressRst, + Masquerade: c.Masquerade, + } + return config, nil +} + type FragmentMask struct { Packets string `json:"packets"` Length Int32Range `json:"length"` diff --git a/infra/conf/transport_internet.go b/infra/conf/transport_internet.go index 24b5fba7c805..eace84880206 100644 --- a/infra/conf/transport_internet.go +++ b/infra/conf/transport_internet.go @@ -17,6 +17,8 @@ func (p TransportProtocol) Build() (string, error) { switch strings.ToLower(string(p)) { case "raw", "tcp": return "tcp", nil + case "rawpacket": + return "rawpacket", nil case "xhttp", "splithttp": return "splithttp", nil case "kcp", "mkcp": @@ -48,6 +50,7 @@ type StreamConfig struct { Network *TransportProtocol `json:"network"` Security string `json:"security"` FinalMask *FinalMask `json:"finalmask"` + RawpacketSettings *RawpacketMask `json:"rawpacketSettings"` TLSSettings *TLSConfig `json:"tlsSettings"` REALITYSettings *REALITYConfig `json:"realitySettings"` RAWSettings *TCPConfig `json:"rawSettings"` @@ -182,6 +185,16 @@ func (c *StreamConfig) Build() (*internet.StreamConfig, error) { Settings: serial.ToTypedMessage(hs), }) } + if c.RawpacketSettings != nil { + rs, err := c.RawpacketSettings.Build() + if err != nil { + return nil, errors.New("Failed to build rawpacket config.").Base(err) + } + config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{ + ProtocolName: "rawpacket", + Settings: serial.ToTypedMessage(rs), + }) + } if c.HysteriaSettings != nil { hs, err := c.HysteriaSettings.Build() if err != nil { diff --git a/main/commands/all/tls/fakehello.go b/main/commands/all/tls/fakehello.go new file mode 100644 index 000000000000..d7d84bca6041 --- /dev/null +++ b/main/commands/all/tls/fakehello.go @@ -0,0 +1,48 @@ +package tls + +import ( + "encoding/base64" + "fmt" + "os" + + "github.com/xtls/xray-core/main/commands/base" + "github.com/xtls/xray-core/transport/internet/finalmask/rawpacket" +) + +var cmdFakeHello = &base.Command{ + UsageLine: "{{.Exec}} tls fake-hello [-hex] ", + Short: "Generate a fake TLS ClientHello payload for rawpacket", + Long: ` +Generate a fake TLS ClientHello for use in finalmask rawpacket settings. + +Arguments: + + -base64 + Output base64-encoded payload (default). + -hex + Output hex-encoded payload instead of base64. +`, +} + +func init() { + cmdFakeHello.Run = executeFakeHello +} + +var fakeHelloHex = cmdFakeHello.Flag.Bool("hex", false, "") + +func executeFakeHello(cmd *base.Command, args []string) { + if cmdFakeHello.Flag.NArg() < 1 { + base.Fatalf("sni not specified") + } + sni := cmdFakeHello.Flag.Arg(0) + payload, err := rawpacket.BuildFakeClientHello(sni) + if err != nil { + base.Fatalf("failed to build ClientHello: %s", err) + } + switch { + case *fakeHelloHex: + fmt.Fprintf(os.Stdout, "%x\n", payload) + default: + fmt.Fprintln(os.Stdout, base64.StdEncoding.EncodeToString(payload)) + } +} diff --git a/main/commands/all/tls/tls.go b/main/commands/all/tls/tls.go index 17a9465a7851..27bc4e8c373c 100644 --- a/main/commands/all/tls/tls.go +++ b/main/commands/all/tls/tls.go @@ -15,5 +15,6 @@ var CmdTLS = &base.Command{ cmdPing, cmdHash, cmdECH, + cmdFakeHello, }, } diff --git a/transport/internet/finalmask/rawpacket/client_hello.go b/transport/internet/finalmask/rawpacket/client_hello.go new file mode 100644 index 000000000000..04eec64584da --- /dev/null +++ b/transport/internet/finalmask/rawpacket/client_hello.go @@ -0,0 +1,51 @@ +package rawpacket + +import ( + "bytes" + "context" + "crypto/tls" + "errors" + "io" + "net" + "time" +) + +// BuildFakeClientHello drives crypto/tls against a write-only in-memory conn +// to capture a generated ClientHello. CurvePreferences pins classical groups +// to suppress Go's default X25519MLKEM768 hybrid key share; without this the +// post-quantum public key alone (~1184 bytes) pushes the record past one MSS, +// and middleboxes do not reassemble fragmented ClientHellos. The handshake +// error is discarded because the stub conn's Read returns immediately. +func BuildFakeClientHello(sni string) ([]byte, error) { + if sni == "" { + return nil, errors.New("empty sni") + } + var buf bytes.Buffer + tlsConn := tls.Client(&writeOnlyConn{w: &buf}, &tls.Config{ + ServerName: sni, + // Order matches what browsers advertised before post-quantum. + CurvePreferences: []tls.CurveID{tls.X25519, tls.CurveP256, tls.CurveP384}, + MinVersion: tls.VersionTLS12, + MaxVersion: tls.VersionTLS13, + NextProtos: []string{"h2", "http/1.1"}, + InsecureSkipVerify: true, + }) + _ = tlsConn.HandshakeContext(context.Background()) + if buf.Len() == 0 { + return nil, errors.New("tls ClientHello not produced") + } + return buf.Bytes(), nil +} + +type writeOnlyConn struct { + w io.Writer +} + +func (c *writeOnlyConn) Read([]byte) (int, error) { return 0, io.EOF } +func (c *writeOnlyConn) Write(p []byte) (int, error) { return c.w.Write(p) } +func (c *writeOnlyConn) Close() error { return nil } +func (c *writeOnlyConn) LocalAddr() net.Addr { return nil } +func (c *writeOnlyConn) RemoteAddr() net.Addr { return nil } +func (c *writeOnlyConn) SetDeadline(time.Time) error { return nil } +func (c *writeOnlyConn) SetReadDeadline(time.Time) error { return nil } +func (c *writeOnlyConn) SetWriteDeadline(time.Time) error { return nil } diff --git a/transport/internet/finalmask/rawpacket/config.go b/transport/internet/finalmask/rawpacket/config.go new file mode 100644 index 000000000000..a82e30ecb36a --- /dev/null +++ b/transport/internet/finalmask/rawpacket/config.go @@ -0,0 +1,60 @@ +package rawpacket + +import ( + "fmt" + "net/netip" + "strings" +) + +const ( + ProtocolTCP uint8 = 6 + ProtocolICMP uint8 = 1 + ProtocolICMPv6 uint8 = 58 + ProtocolUDP uint8 = 17 +) + +func ParseProtocol(s string) (uint8, error) { + switch strings.ToLower(s) { + case "tcp": + return ProtocolTCP, nil + case "icmp": + return ProtocolICMP, nil + case "icmpv6": + return ProtocolICMPv6, nil + case "udp": + return ProtocolUDP, nil + default: + return 0, fmt.Errorf("rawpacket: unknown protocol: %s", s) + } +} + +func ParseIPs(ss []string) ([]netip.Addr, error) { + var out []netip.Addr + for _, s := range ss { + ip, err := netip.ParseAddr(s) + if err != nil { + return nil, fmt.Errorf("rawpacket: invalid spoof IP %q: %w", s, err) + } + out = append(out, ip.Unmap()) + } + return out, nil +} + +type RelayConfig struct { + ListenPort uint16 + ForwardAddr string + ForwardTransport string // "tcp" (Xray) or "udp" (reference, default) + ClientIP netip.Addr + ClientPort uint16 + SpoofIP netip.Addr // single fallback + SpoofIPs []string + SpoofPort uint16 + PeerSpoofIP netip.Addr + SendTransport string + RecvTransport string + Mtu uint32 + SuppressRst bool + Masquerade string // "off" | "http" | "tls" | "dns" + Auth []byte + icmpSuppressed bool +} diff --git a/transport/internet/finalmask/rawpacket/config.pb.go b/transport/internet/finalmask/rawpacket/config.pb.go new file mode 100644 index 000000000000..3704f09f977f --- /dev/null +++ b/transport/internet/finalmask/rawpacket/config.pb.go @@ -0,0 +1,326 @@ +// Code generated by protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.36.11 +// protoc v7.35.1 +// source: transport/internet/finalmask/rawpacket/config.proto + +package rawpacket + +import ( + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" + reflect "reflect" + sync "sync" + unsafe "unsafe" +) + +const ( + // Verify that this generated code is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) + // Verify that runtime/protoimpl is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) +) + +type Config struct { + state protoimpl.MessageState `protogen:"open.v1"` + // Mode: "local" (client) or "remote" (server). + Mode string `protobuf:"bytes,6,opt,name=mode,proto3" json:"mode,omitempty"` + // Remote server address (local/client mode). + RemoteAddress string `protobuf:"bytes,7,opt,name=remote_address,json=remoteAddress,proto3" json:"remote_address,omitempty"` + // Remote server port (client mode). + RemotePort uint32 `protobuf:"varint,8,opt,name=remote_port,json=remotePort,proto3" json:"remote_port,omitempty"` + // Local port for receiving responses from the relay (client mode). + RecvPort uint32 `protobuf:"varint,9,opt,name=recv_port,json=recvPort,proto3" json:"recv_port,omitempty"` + // List of IP addresses to spoof as source. + SpoofIps []string `protobuf:"bytes,10,rep,name=spoof_ips,json=spoofIps,proto3" json:"spoof_ips,omitempty"` + // List of transport protocols to use: tcp, udp, icmp, icmpv6. + Protocols []string `protobuf:"bytes,11,rep,name=protocols,proto3" json:"protocols,omitempty"` + // MTU for packet fragmentation. + Mtu uint32 `protobuf:"varint,12,opt,name=mtu,proto3" json:"mtu,omitempty"` + // Target address for the relay (e.g. "127.0.0.1:443"). + Target string `protobuf:"bytes,13,opt,name=target,proto3" json:"target,omitempty"` + // TTL for outgoing packets. + Ttl uint32 `protobuf:"varint,14,opt,name=ttl,proto3" json:"ttl,omitempty"` + // Send transport: "tcp", "udp", "icmp", "icmpv6" (default: "tcp"). + SendTransport string `protobuf:"bytes,15,opt,name=send_transport,json=sendTransport,proto3" json:"send_transport,omitempty"` + // Receive transport: "tcp", "udp", "icmp", "icmpv6" (default: "udp"). + RecvTransport string `protobuf:"bytes,16,opt,name=recv_transport,json=recvTransport,proto3" json:"recv_transport,omitempty"` + // Relay address (for the relay sender, defaults to first spoof IP). + RelayAddress string `protobuf:"bytes,17,opt,name=relay_address,json=relayAddress,proto3" json:"relay_address,omitempty"` + // Port the relay listens on (remote/server mode). + RelayPort uint32 `protobuf:"varint,18,opt,name=relay_port,json=relayPort,proto3" json:"relay_port,omitempty"` + // Client IP address (remote/server mode) — where to send responses. + ClientIp string `protobuf:"bytes,19,opt,name=client_ip,json=clientIp,proto3" json:"client_ip,omitempty"` + // Client port (remote/server mode). + ClientPort uint32 `protobuf:"varint,20,opt,name=client_port,json=clientPort,proto3" json:"client_port,omitempty"` + // Expected peer spoof IP for receive filtering (nil = accept all). + PeerSpoofIp string `protobuf:"bytes,21,opt,name=peer_spoof_ip,json=peerSpoofIp,proto3" json:"peer_spoof_ip,omitempty"` + // Source port to use in spoofed packets (default: 443). + SpoofPort uint32 `protobuf:"varint,22,opt,name=spoof_port,json=spoofPort,proto3" json:"spoof_port,omitempty"` + // Pre-shared key authenticating and encrypting the tunnel. Required + // in both modes; must match on client and relay. + Auth string `protobuf:"bytes,23,opt,name=auth,proto3" json:"auth,omitempty"` + // Suppress kernel-generated TCP RST for the relay's listen port + // (Linux only; uses iptables OUTPUT REJECT rules). Prevents the kernel + // from answering the fake TCP handshake with RST. + SuppressRst bool `protobuf:"varint,24,opt,name=suppress_rst,json=suppressRst,proto3" json:"suppress_rst,omitempty"` + // Masquerade for non-tunnel traffic (probes, scanners): "http" or + // "tls" serve a fake web service to TCP probes, "dns" answers UDP + // queries. Empty or "off" disables. + Masquerade string `protobuf:"bytes,26,opt,name=masquerade,proto3" json:"masquerade,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *Config) Reset() { + *x = Config{} + mi := &file_transport_internet_finalmask_rawpacket_config_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *Config) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*Config) ProtoMessage() {} + +func (x *Config) ProtoReflect() protoreflect.Message { + mi := &file_transport_internet_finalmask_rawpacket_config_proto_msgTypes[0] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use Config.ProtoReflect.Descriptor instead. +func (*Config) Descriptor() ([]byte, []int) { + return file_transport_internet_finalmask_rawpacket_config_proto_rawDescGZIP(), []int{0} +} + +func (x *Config) GetMode() string { + if x != nil { + return x.Mode + } + return "" +} + +func (x *Config) GetRemoteAddress() string { + if x != nil { + return x.RemoteAddress + } + return "" +} + +func (x *Config) GetRemotePort() uint32 { + if x != nil { + return x.RemotePort + } + return 0 +} + +func (x *Config) GetRecvPort() uint32 { + if x != nil { + return x.RecvPort + } + return 0 +} + +func (x *Config) GetSpoofIps() []string { + if x != nil { + return x.SpoofIps + } + return nil +} + +func (x *Config) GetProtocols() []string { + if x != nil { + return x.Protocols + } + return nil +} + +func (x *Config) GetMtu() uint32 { + if x != nil { + return x.Mtu + } + return 0 +} + +func (x *Config) GetTarget() string { + if x != nil { + return x.Target + } + return "" +} + +func (x *Config) GetTtl() uint32 { + if x != nil { + return x.Ttl + } + return 0 +} + +func (x *Config) GetSendTransport() string { + if x != nil { + return x.SendTransport + } + return "" +} + +func (x *Config) GetRecvTransport() string { + if x != nil { + return x.RecvTransport + } + return "" +} + +func (x *Config) GetRelayAddress() string { + if x != nil { + return x.RelayAddress + } + return "" +} + +func (x *Config) GetRelayPort() uint32 { + if x != nil { + return x.RelayPort + } + return 0 +} + +func (x *Config) GetClientIp() string { + if x != nil { + return x.ClientIp + } + return "" +} + +func (x *Config) GetClientPort() uint32 { + if x != nil { + return x.ClientPort + } + return 0 +} + +func (x *Config) GetPeerSpoofIp() string { + if x != nil { + return x.PeerSpoofIp + } + return "" +} + +func (x *Config) GetSpoofPort() uint32 { + if x != nil { + return x.SpoofPort + } + return 0 +} + +func (x *Config) GetAuth() string { + if x != nil { + return x.Auth + } + return "" +} + +func (x *Config) GetSuppressRst() bool { + if x != nil { + return x.SuppressRst + } + return false +} + +func (x *Config) GetMasquerade() string { + if x != nil { + return x.Masquerade + } + return "" +} + +var File_transport_internet_finalmask_rawpacket_config_proto protoreflect.FileDescriptor + +const file_transport_internet_finalmask_rawpacket_config_proto_rawDesc = "" + + "\n" + + "3transport/internet/finalmask/rawpacket/config.proto\x12+xray.transport.internet.finalmask.rawpacket\"\xe2\x04\n" + + "\x06Config\x12\x12\n" + + "\x04mode\x18\x06 \x01(\tR\x04mode\x12%\n" + + "\x0eremote_address\x18\a \x01(\tR\rremoteAddress\x12\x1f\n" + + "\vremote_port\x18\b \x01(\rR\n" + + "remotePort\x12\x1b\n" + + "\trecv_port\x18\t \x01(\rR\brecvPort\x12\x1b\n" + + "\tspoof_ips\x18\n" + + " \x03(\tR\bspoofIps\x12\x1c\n" + + "\tprotocols\x18\v \x03(\tR\tprotocols\x12\x10\n" + + "\x03mtu\x18\f \x01(\rR\x03mtu\x12\x16\n" + + "\x06target\x18\r \x01(\tR\x06target\x12\x10\n" + + "\x03ttl\x18\x0e \x01(\rR\x03ttl\x12%\n" + + "\x0esend_transport\x18\x0f \x01(\tR\rsendTransport\x12%\n" + + "\x0erecv_transport\x18\x10 \x01(\tR\rrecvTransport\x12#\n" + + "\rrelay_address\x18\x11 \x01(\tR\frelayAddress\x12\x1d\n" + + "\n" + + "relay_port\x18\x12 \x01(\rR\trelayPort\x12\x1b\n" + + "\tclient_ip\x18\x13 \x01(\tR\bclientIp\x12\x1f\n" + + "\vclient_port\x18\x14 \x01(\rR\n" + + "clientPort\x12\"\n" + + "\rpeer_spoof_ip\x18\x15 \x01(\tR\vpeerSpoofIp\x12\x1d\n" + + "\n" + + "spoof_port\x18\x16 \x01(\rR\tspoofPort\x12\x12\n" + + "\x04auth\x18\x17 \x01(\tR\x04auth\x12!\n" + + "\fsuppress_rst\x18\x18 \x01(\bR\vsuppressRst\x12\x1e\n" + + "\n" + + "masquerade\x18\x1a \x01(\tR\n" + + "masqueradeB\xa3\x01\n" + + "/com.xray.transport.internet.finalmask.rawpacketP\x01Z@github.com/xtls/xray-core/transport/internet/finalmask/rawpacket\xaa\x02+Xray.Transport.Internet.Finalmask.Rawpacketb\x06proto3" + +var ( + file_transport_internet_finalmask_rawpacket_config_proto_rawDescOnce sync.Once + file_transport_internet_finalmask_rawpacket_config_proto_rawDescData []byte +) + +func file_transport_internet_finalmask_rawpacket_config_proto_rawDescGZIP() []byte { + file_transport_internet_finalmask_rawpacket_config_proto_rawDescOnce.Do(func() { + file_transport_internet_finalmask_rawpacket_config_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_transport_internet_finalmask_rawpacket_config_proto_rawDesc), len(file_transport_internet_finalmask_rawpacket_config_proto_rawDesc))) + }) + return file_transport_internet_finalmask_rawpacket_config_proto_rawDescData +} + +var file_transport_internet_finalmask_rawpacket_config_proto_msgTypes = make([]protoimpl.MessageInfo, 1) +var file_transport_internet_finalmask_rawpacket_config_proto_goTypes = []any{ + (*Config)(nil), // 0: xray.transport.internet.finalmask.rawpacket.Config +} +var file_transport_internet_finalmask_rawpacket_config_proto_depIdxs = []int32{ + 0, // [0:0] is the sub-list for method output_type + 0, // [0:0] is the sub-list for method input_type + 0, // [0:0] is the sub-list for extension type_name + 0, // [0:0] is the sub-list for extension extendee + 0, // [0:0] is the sub-list for field type_name +} + +func init() { file_transport_internet_finalmask_rawpacket_config_proto_init() } +func file_transport_internet_finalmask_rawpacket_config_proto_init() { + if File_transport_internet_finalmask_rawpacket_config_proto != nil { + return + } + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: unsafe.Slice(unsafe.StringData(file_transport_internet_finalmask_rawpacket_config_proto_rawDesc), len(file_transport_internet_finalmask_rawpacket_config_proto_rawDesc)), + NumEnums: 0, + NumMessages: 1, + NumExtensions: 0, + NumServices: 0, + }, + GoTypes: file_transport_internet_finalmask_rawpacket_config_proto_goTypes, + DependencyIndexes: file_transport_internet_finalmask_rawpacket_config_proto_depIdxs, + MessageInfos: file_transport_internet_finalmask_rawpacket_config_proto_msgTypes, + }.Build() + File_transport_internet_finalmask_rawpacket_config_proto = out.File + file_transport_internet_finalmask_rawpacket_config_proto_goTypes = nil + file_transport_internet_finalmask_rawpacket_config_proto_depIdxs = nil +} diff --git a/transport/internet/finalmask/rawpacket/config.proto b/transport/internet/finalmask/rawpacket/config.proto new file mode 100644 index 000000000000..82f83023701a --- /dev/null +++ b/transport/internet/finalmask/rawpacket/config.proto @@ -0,0 +1,74 @@ +syntax = "proto3"; + +package xray.transport.internet.finalmask.rawpacket; +option csharp_namespace = "Xray.Transport.Internet.Finalmask.Rawpacket"; +option go_package = "github.com/xtls/xray-core/transport/internet/finalmask/rawpacket"; +option java_package = "com.xray.transport.internet.finalmask.rawpacket"; +option java_multiple_files = true; + +message Config { + // Mode: "local" (client) or "remote" (server). + string mode = 6; + + // Remote server address (local/client mode). + string remote_address = 7; + + // Remote server port (client mode). + uint32 remote_port = 8; + + // Local port for receiving responses from the relay (client mode). + uint32 recv_port = 9; + + // List of IP addresses to spoof as source. + repeated string spoof_ips = 10; + + // List of transport protocols to use: tcp, udp, icmp, icmpv6. + repeated string protocols = 11; + + // MTU for packet fragmentation. + uint32 mtu = 12; + + // Target address for the relay (e.g. "127.0.0.1:443"). + string target = 13; + + // TTL for outgoing packets. + uint32 ttl = 14; + + // Send transport: "tcp", "udp", "icmp", "icmpv6" (default: "tcp"). + string send_transport = 15; + + // Receive transport: "tcp", "udp", "icmp", "icmpv6" (default: "udp"). + string recv_transport = 16; + + // Relay address (for the relay sender, defaults to first spoof IP). + string relay_address = 17; + + // Port the relay listens on (remote/server mode). + uint32 relay_port = 18; + + // Client IP address (remote/server mode) — where to send responses. + string client_ip = 19; + + // Client port (remote/server mode). + uint32 client_port = 20; + + // Expected peer spoof IP for receive filtering (nil = accept all). + string peer_spoof_ip = 21; + + // Source port to use in spoofed packets (default: 443). + uint32 spoof_port = 22; + + // Pre-shared key authenticating and encrypting the tunnel. Required + // in both modes; must match on client and relay. + string auth = 23; + + // Suppress kernel-generated TCP RST for the relay's listen port + // (Linux only; uses iptables OUTPUT REJECT rules). Prevents the kernel + // from answering the fake TCP handshake with RST. + bool suppress_rst = 24; + + // Masquerade for non-tunnel traffic (probes, scanners): "http" or + // "tls" serve a fake web service to TCP probes, "dns" answers UDP + // queries. Empty or "off" disables. + string masquerade = 26; +} diff --git a/transport/internet/finalmask/rawpacket/config_register.go b/transport/internet/finalmask/rawpacket/config_register.go new file mode 100644 index 000000000000..29f830504da1 --- /dev/null +++ b/transport/internet/finalmask/rawpacket/config_register.go @@ -0,0 +1,74 @@ +package rawpacket + +import ( + "context" + stdnet "net" + + "github.com/xtls/xray-core/common" + "github.com/xtls/xray-core/common/net" + "github.com/xtls/xray-core/transport/internet" + "github.com/xtls/xray-core/transport/internet/stat" +) + +const ProtocolName = "rawpacket" + +type rawpacketListener struct { + addr stdnet.Addr + done chan struct{} + relay *Relay +} + +func (l *rawpacketListener) Close() error { + if l.relay != nil { + l.relay.Close() + } + close(l.done) + return nil +} + +func (l *rawpacketListener) Addr() stdnet.Addr { + return l.addr +} + +func init() { + common.Must(internet.RegisterProtocolConfigCreator(ProtocolName, func() interface{} { + return new(Config) + })) + common.Must(internet.RegisterTransportDialer(ProtocolName, Dial)) + common.Must(internet.RegisterTransportListener(ProtocolName, listenRawpacket)) +} + +func listenRawpacket(ctx context.Context, address net.Address, port net.Port, settings *internet.MemoryStreamConfig, handler internet.ConnHandler) (internet.Listener, error) { + config := settings.ProtocolSettings.(*Config) + if config.Mode == "remote" { + cfg, err := config.buildRelayConfig() + if err == nil { + if cfg.ListenPort == 0 { + cfg.ListenPort = uint16(port) + } + r, err := NewRelay(cfg) + if err == nil { + go r.Run() + return &rawpacketListener{ + addr: &stdnet.TCPAddr{IP: stdnet.IP{0, 0, 0, 0}, Port: int(port)}, + done: make(chan struct{}), + relay: r, + }, nil + } + } + } + return &rawpacketListener{ + addr: &stdnet.TCPAddr{IP: stdnet.IP{0, 0, 0, 0}, Port: int(port)}, + done: make(chan struct{}), + }, nil +} + +func Dial(ctx context.Context, dest net.Destination, streamSettings *internet.MemoryStreamConfig) (stat.Connection, error) { + config := streamSettings.ProtocolSettings.(*Config) + + conn, err := config.WrapConnClient(nil) + if err != nil { + return nil, err + } + return stat.Connection(conn), nil +} diff --git a/transport/internet/finalmask/rawpacket/conn.go b/transport/internet/finalmask/rawpacket/conn.go new file mode 100644 index 000000000000..c4c4dde4af81 --- /dev/null +++ b/transport/internet/finalmask/rawpacket/conn.go @@ -0,0 +1,185 @@ +package rawpacket + +import ( + "fmt" + "net" + "net/netip" + "strconv" +) + +func (c *Config) TCP() {} + +func (c *Config) WrapConnClient(raw net.Conn) (net.Conn, error) { + if !PlatformSupported { + return nil, fmt.Errorf("rawpacket is not supported on this platform") + } + + mode := c.Mode + if mode == "" { + mode = "local" + } + + switch mode { + case "local": + return c.dialLocal() + case "remote": + return nil, fmt.Errorf("rawpacket: remote mode must be used as server") + default: + return nil, fmt.Errorf("rawpacket: unknown mode: %s", mode) + } +} + +func (c *Config) WrapConnServer(raw net.Conn) (net.Conn, error) { + // The relay is owned and started by the listener (listenRawpacket); + // starting it here too would run two relays over the same port. + return raw, nil +} + +func toNetIP(s string) net.IP { + if s == "" { + return nil + } + return net.ParseIP(s) +} + +func toNetipAddr(s string) netip.Addr { + if s == "" { + return netip.Addr{} + } + ip, err := netip.ParseAddr(s) + if err != nil { + return netip.Addr{} + } + return ip.Unmap() +} + +func (c *Config) dialLocal() (net.Conn, error) { + remoteIP := c.RemoteAddress + if remoteIP == "" { + return nil, fmt.Errorf("rawpacket: remoteAddress required") + } + remotePort := uint16(c.RemotePort) + if remotePort == 0 { + remotePort = 443 + } + + recvPort := uint16(c.RecvPort) + if recvPort == 0 { + recvPort = 60000 + } + + spoofIPs := c.SpoofIps + if len(spoofIPs) == 0 { + return nil, fmt.Errorf("rawpacket: at least one spoof IP required") + } + + ttl := uint8(c.Ttl) + if ttl == 0 { + ttl = 64 + } + + sendProto := c.SendTransport + if sendProto == "" { + sendProto = "tcp" + } + + recvProto := c.RecvTransport + if recvProto == "" { + recvProto = "udp" + } + + relayAddrPort, err := netip.ParseAddrPort(net.JoinHostPort(remoteIP, strconv.Itoa(int(remotePort)))) + if err != nil { + return nil, fmt.Errorf("rawpacket: parse remote address: %w", err) + } + + ips, err := ParseIPs(spoofIPs) + if err != nil { + return nil, err + } + + if c.Auth == "" { + return nil, fmt.Errorf("rawpacket: auth (PSK) required in local mode") + } + + return DialSpoof(relayAddrPort, ips, recvPort, ttl, c.Mtu, sendProto, recvProto, toNetipAddr(c.PeerSpoofIp), []byte(c.Auth)) +} + +func (c *Config) buildRelayConfig() (*RelayConfig, error) { + spoofIPs := c.SpoofIps + if len(spoofIPs) == 0 { + return nil, fmt.Errorf("rawpacket: at least one spoof IP required for relay") + } + if c.Auth == "" { + return nil, fmt.Errorf("rawpacket: auth (PSK) required in remote mode") + } + + target := c.Target + if target == "" { + target = "127.0.0.1:443" + } + + relayPort := uint16(c.RelayPort) + if relayPort == 0 { + relayPort = 443 + } + + sendProto := c.SendTransport + if sendProto == "" { + sendProto = "udp" + } + + recvProto := c.RecvTransport + if recvProto == "" { + recvProto = "tcp" + } + + clientIP := c.ClientIp + clientPort := uint16(c.ClientPort) + + if clientIP == "" { + clientIP = firstStr(spoofIPs) + } + if clientPort == 0 { + clientPort = uint16(c.RecvPort) + if clientPort == 0 { + clientPort = 60000 + } + } + + spoofPort := uint16(c.SpoofPort) + if spoofPort == 0 { + spoofPort = 443 + } + + fwdTransport := c.SendTransport + if fwdTransport == "udp" { + fwdTransport = "udp" + } else { + fwdTransport = "tcp" + } + + return &RelayConfig{ + ListenPort: relayPort, + ForwardAddr: target, + ForwardTransport: fwdTransport, + ClientIP: toNetipAddr(clientIP), + ClientPort: clientPort, + SpoofIPs: spoofIPs, + SpoofPort: spoofPort, + PeerSpoofIP: toNetipAddr(c.PeerSpoofIp), + SendTransport: sendProto, + RecvTransport: recvProto, + Mtu: c.Mtu, + SuppressRst: c.SuppressRst, + Masquerade: c.Masquerade, + Auth: []byte(c.Auth), + }, nil +} + +func firstStr(ss []string) string { + if len(ss) > 0 { + return ss[0] + } + return "" +} diff --git a/transport/internet/finalmask/rawpacket/frame.go b/transport/internet/finalmask/rawpacket/frame.go new file mode 100644 index 000000000000..33d14ec5aff1 --- /dev/null +++ b/transport/internet/finalmask/rawpacket/frame.go @@ -0,0 +1,323 @@ +package rawpacket + +import ( + "crypto/aes" + "crypto/cipher" + "crypto/rand" + "crypto/sha256" + "encoding/binary" + "errors" + "io" + "sync" + + "golang.org/x/crypto/hkdf" +) + +// Frame layout (all integers big-endian): +// +// 0:4 magic (0x58445250 "XRDP") +// 4:1 version (1) +// 5:1 flags +// 6:2 reserved (zero) +// 8:16 session ID (random, chosen by the client per connection) +// 16:4 sequence number (per direction, starting at 0) +// 20:2 payload length +// 22:8 nonce (seq BE || direction byte || zeros) +// 30: AES-256-GCM ciphertext || tag +// +// The header prefix (bytes 0..22) is authenticated as GCM AAD, so any +// modification of magic/version/flags/reserved/session/seq/len is +// detected. Direction byte in the nonce: 0 = client->relay, 1 = relay->client. +const ( + frameMagic uint32 = 0x58445250 + frameVersion byte = 1 + frameHeaderLen = 30 + frameTagLen = 16 + frameNonceLen = 8 + frameAADLen = 22 + frameOverhead = frameHeaderLen + frameTagLen + + frameFlagKeepalive byte = 0x01 + frameFlagServer byte = 0x02 + + // frameMaxPayload caps each datagram so the full frame fits inside a + // single unfragmented packet on typical links (1400 + 46 < 1480). + frameMaxPayload = 1400 +) + +var ( + errFrameShort = errors.New("rawpacket: frame too short") + errFrameBad = errors.New("rawpacket: invalid frame") + errFrameAuth = errors.New("rawpacket: frame authentication failed") + errFrameReplay = errors.New("rawpacket: frame replay rejected") +) + +// replayWindow is a sliding-window anti-replay filter for a single +// direction of a session (RFC 4303 style). The window covers the highest +// received sequence number and the replayWindowSize-1 sequence numbers +// below it, so packets may arrive up to replayWindowSize-1 out of order. +// Every sequence number is accepted exactly once. +type replayWindow struct { + base uint32 + bitmap uint64 +} + +const replayWindowSize = 64 + +// accept reports whether seq has not been seen before. Bit i of bitmap +// records seq = base - (replayWindowSize - 1 - i); bit 63 is base. +func (w *replayWindow) accept(seq uint32) bool { + if w.base == 0 && w.bitmap == 0 { + w.base = seq + w.bitmap = 1 << (replayWindowSize - 1) + return true + } + diff := int32(seq - w.base) + switch { + case diff > 0: + if diff < int32(replayWindowSize) { + // Advance: old entries shift down, new seq lands on top. + w.bitmap >>= uint(diff) + w.bitmap |= 1 << (replayWindowSize - 1) + } else { + // Jump: the whole old window is discarded. + w.bitmap = 1 << (replayWindowSize - 1) + } + w.base = seq + return true + case diff < 0: + offset := int32(replayWindowSize) - 1 + diff + if offset < 0 { + return false + } + bit := uint64(1) << uint(offset) + if w.bitmap&bit != 0 { + return false + } + w.bitmap |= bit + return true + default: + // seq == base: duplicate unless the top bit is somehow clear. + if w.bitmap&(1<<(replayWindowSize-1)) != 0 { + return false + } + w.bitmap |= 1 << (replayWindowSize - 1) + return true + } +} + +// frameCrypto owns the per-session keys and per-direction sequence/replay +// state. One instance exists per session on each side. The two directions +// have independent mutexes so uplink and downlink never contend. +type frameCrypto struct { + sid [8]byte + clientAEAD cipher.AEAD + serverAEAD cipher.AEAD + + clientSeq uint32 + serverSeq uint32 + clientRep replayWindow + serverRep replayWindow + + clientMu sync.Mutex + serverMu sync.Mutex +} + +func newFrameCrypto(psk []byte, sid [8]byte) (*frameCrypto, error) { + clientKey, err := deriveFrameKey(psk, sid, []byte("rawpacket-client-v1")) + if err != nil { + return nil, err + } + serverKey, err := deriveFrameKey(psk, sid, []byte("rawpacket-server-v1")) + if err != nil { + return nil, err + } + clientAEAD, err := newGCM(clientKey) + if err != nil { + return nil, err + } + serverAEAD, err := newGCM(serverKey) + if err != nil { + return nil, err + } + return &frameCrypto{ + sid: sid, + clientAEAD: clientAEAD, + serverAEAD: serverAEAD, + }, nil +} + +func deriveFrameKey(psk []byte, sid [8]byte, info []byte) ([]byte, error) { + key := make([]byte, 32) + r := hkdf.New(sha256.New, psk, sid[:], info) + if _, err := io.ReadFull(r, key); err != nil { + return nil, err + } + return key, nil +} + +func newGCM(key []byte) (cipher.AEAD, error) { + block, err := aes.NewCipher(key) + if err != nil { + return nil, err + } + return cipher.NewGCMWithNonceSize(block, frameNonceLen) +} + +func newSessionID() ([8]byte, error) { + var sid [8]byte + if _, err := rand.Read(sid[:]); err != nil { + return sid, err + } + return sid, nil +} + +func frameNonce(seq uint32, server bool) [frameNonceLen]byte { + var n [frameNonceLen]byte + binary.BigEndian.PutUint32(n[0:4], seq) + if server { + n[4] = 1 + } + return n +} + +// seal builds and encrypts one frame from payload. server selects the +// relay->client direction. The sequence counter and replay window are +// updated. Payload is capped at frameMaxPayload. +func (f *frameCrypto) seal(server bool, payload []byte, keepalive bool) ([]byte, error) { + if len(payload) > frameMaxPayload { + return nil, errors.New("rawpacket: payload exceeds frameMaxPayload") + } + if server { + f.serverMu.Lock() + defer f.serverMu.Unlock() + } else { + f.clientMu.Lock() + defer f.clientMu.Unlock() + } + + seq := f.clientSeq + var aead cipher.AEAD + if server { + seq = f.serverSeq + f.serverSeq++ + aead = f.serverAEAD + } else { + seq = f.clientSeq + f.clientSeq++ + aead = f.clientAEAD + } + + flags := byte(0) + if server { + flags |= frameFlagServer + } + if keepalive { + flags |= frameFlagKeepalive + } + + out := make([]byte, frameHeaderLen+len(payload)+frameTagLen) + binary.BigEndian.PutUint32(out[0:4], frameMagic) + out[4] = frameVersion + out[5] = flags + // 6:7 reserved + copy(out[8:16], f.sid[:]) + binary.BigEndian.PutUint32(out[16:20], seq) + binary.BigEndian.PutUint16(out[20:22], uint16(len(payload))) + + nonce := frameNonce(seq, server) + aead.Seal(out[frameHeaderLen:frameHeaderLen], nonce[:], payload, out[:frameAADLen]) + return out, nil +} + +// open parses, authenticates and decrypts one frame. server selects the +// direction the frame is expected from. The returned payload is freshly +// allocated and safe to retain. +func (f *frameCrypto) open(b []byte, server bool) (payload []byte, flags byte, err error) { + if len(b) < frameHeaderLen+frameTagLen { + return nil, 0, errFrameShort + } + if binary.BigEndian.Uint32(b[0:4]) != frameMagic || b[4] != frameVersion { + return nil, 0, errFrameBad + } + flags = b[5] + if (flags&frameFlagServer != 0) != server { + return nil, 0, errFrameBad + } + pLen := int(binary.BigEndian.Uint16(b[20:22])) + if pLen != len(b)-frameHeaderLen-frameTagLen { + return nil, 0, errFrameBad + } + seq := binary.BigEndian.Uint32(b[16:20]) + + if server { + f.serverMu.Lock() + defer f.serverMu.Unlock() + } else { + f.clientMu.Lock() + defer f.clientMu.Unlock() + } + + var aead cipher.AEAD + var rep *replayWindow + if server { + aead = f.serverAEAD + rep = &f.serverRep + } else { + aead = f.clientAEAD + rep = &f.clientRep + } + if !rep.accept(seq) { + return nil, 0, errFrameReplay + } + nonce := frameNonce(seq, server) + ct := b[frameHeaderLen : frameHeaderLen+pLen+frameTagLen] + pt, err := aead.Open(nil, nonce[:], ct, b[:frameAADLen]) + if err != nil { + return nil, 0, errFrameAuth + } + return pt, flags, nil +} + +// frameSessionID extracts the session ID from a frame header without +// decrypting it. Returns false for non-frame traffic (which the relay must +// silently ignore: real TLS, kernel noise, etc.). +func frameSessionID(b []byte) (sid [8]byte, ok bool) { + if len(b) < frameHeaderLen { + return sid, false + } + if binary.BigEndian.Uint32(b[0:4]) != frameMagic || b[4] != frameVersion { + return sid, false + } + copy(sid[:], b[8:16]) + return sid, true +} + +// sealSplit splits a large payload into frames of at most maxPayload and +// seals each one in sequence order. +func (f *frameCrypto) sealSplit(server bool, payload []byte, maxPayload int, keepalive bool) ([][]byte, error) { + if maxPayload <= 0 { + maxPayload = frameMaxPayload + } + if len(payload) == 0 { + frame, err := f.seal(server, nil, keepalive) + if err != nil { + return nil, err + } + return [][]byte{frame}, nil + } + frames := make([][]byte, 0, (len(payload)+maxPayload-1)/maxPayload) + for len(payload) > 0 { + chunk := payload + if len(chunk) > maxPayload { + chunk = chunk[:maxPayload] + } + frame, err := f.seal(server, chunk, false) + if err != nil { + return nil, err + } + frames = append(frames, frame) + payload = payload[len(chunk):] + } + return frames, nil +} diff --git a/transport/internet/finalmask/rawpacket/frame_demux.go b/transport/internet/finalmask/rawpacket/frame_demux.go new file mode 100644 index 000000000000..0ec2ebd1bd3b --- /dev/null +++ b/transport/internet/finalmask/rawpacket/frame_demux.go @@ -0,0 +1,141 @@ +package rawpacket + +import ( + "net/netip" + "sync" +) + +// frameDemux demultiplexes decrypted relay->client frames to per-conn +// consumers. Multiple SpoofConns on the same host share one raw receiver +// per (protocol, listen port); a raw socket delivers a copy of every +// matching packet to every socket, so the receiver must be shared or +// frames would be duplicated across connections. +type frameDemux struct { + proto string + port uint16 + peerIP netip.Addr + + mu sync.Mutex + sessions map[[8]byte]*demuxSession + recver SpoofReceiver + refs int + running bool + gen uint64 +} + +type demuxSession struct { + crypto *frameCrypto + ch chan demuxData +} + +// demuxData is one decrypted relay->client payload with the originating +// TCP header metadata (for sequence/ack state tracking). +type demuxData struct { + payload []byte + tcp *TCPMeta +} + +type demuxKey struct { + proto string + port uint16 +} + +var demuxRegistry sync.Map // demuxKey -> *frameDemux + +func getFrameDemux(proto string, port uint16, peerIP netip.Addr) *frameDemux { + key := demuxKey{proto: proto, port: port} + if d, ok := demuxRegistry.Load(key); ok { + return d.(*frameDemux) + } + d := &frameDemux{ + proto: proto, + port: port, + peerIP: peerIP, + sessions: make(map[[8]byte]*demuxSession), + } + actual, _ := demuxRegistry.LoadOrStore(key, d) + return actual.(*frameDemux) +} + +// register subscribes sid to the demux, starting the shared receiver and +// demux goroutine on first use. +func (d *frameDemux) register(sid [8]byte, crypto *frameCrypto, ch chan demuxData) error { + d.mu.Lock() + defer d.mu.Unlock() + d.sessions[sid] = &demuxSession{crypto: crypto, ch: ch} + d.refs++ + if d.running { + return nil + } + recver, err := NewReceiver(d.proto, &SpoofReceiverConfig{ + ListenPort: d.port, + PeerSpoofIP: d.peerIP, + BufferSize: 4 * 1024 * 1024, + }) + if err != nil { + delete(d.sessions, sid) + d.refs-- + return err + } + d.recver = recver + d.running = true + d.gen++ + go d.run(d.gen) + return nil +} + +func (d *frameDemux) unregister(sid [8]byte) { + d.mu.Lock() + defer d.mu.Unlock() + delete(d.sessions, sid) + d.refs-- + if d.refs > 0 || !d.running { + return + } + d.running = false + d.recver.Close() + d.recver = nil + demuxRegistry.Delete(demuxKey{proto: d.proto, port: d.port}) +} + +func (d *frameDemux) run(gen uint64) { + for { + pkt, _, _, tcp, err := d.recver.Receive() + if err != nil { + d.mu.Lock() + if d.gen != gen { + // Superseded by a newer generation (the demux was torn + // down and restarted): leave the new sessions alone. + d.mu.Unlock() + return + } + // Receiver died unexpectedly (or the demux was torn down): + // unblock every consumer. + for _, s := range d.sessions { + close(s.ch) + } + d.sessions = make(map[[8]byte]*demuxSession) + d.running = false + d.mu.Unlock() + return + } + sid, ok := frameSessionID(pkt) + if !ok { + continue + } + d.mu.Lock() + s := d.sessions[sid] + d.mu.Unlock() + if s == nil { + continue + } + payload, flags, err := s.crypto.open(pkt, true) + if err != nil || flags&frameFlagKeepalive != 0 || len(payload) == 0 { + continue + } + select { + case s.ch <- demuxData{payload: payload, tcp: tcp}: + default: // consumer is slow: drop rather than stall the demux + } + } +} diff --git a/transport/internet/finalmask/rawpacket/frame_test.go b/transport/internet/finalmask/rawpacket/frame_test.go new file mode 100644 index 000000000000..84c5c2279758 --- /dev/null +++ b/transport/internet/finalmask/rawpacket/frame_test.go @@ -0,0 +1,283 @@ +package rawpacket + +import ( + "bytes" + "crypto/rand" + "testing" +) + +func testFrameCrypto(t *testing.T) *frameCrypto { + t.Helper() + psk := []byte("test-psk-secret") + var sid [8]byte + if _, err := rand.Read(sid[:]); err != nil { + t.Fatal(err) + } + f, err := newFrameCrypto(psk, sid) + if err != nil { + t.Fatal(err) + } + return f +} + +func TestFrameSealOpenRoundTrip(t *testing.T) { + f := testFrameCrypto(t) + payload := []byte("hello rawpacket") + + frame, err := f.seal(false, payload, false) + if err != nil { + t.Fatal(err) + } + got, flags, err := f.open(frame, false) + if err != nil { + t.Fatalf("open: %v", err) + } + if !bytes.Equal(got, payload) { + t.Fatalf("payload mismatch: got %q", got) + } + if flags&frameFlagServer != 0 { + t.Fatal("client frame must not carry server flag") + } + + frame, err = f.seal(true, payload, true) + if err != nil { + t.Fatal(err) + } + got, flags, err = f.open(frame, true) + if err != nil { + t.Fatalf("open server frame: %v", err) + } + if !bytes.Equal(got, payload) { + t.Fatalf("payload mismatch: got %q", got) + } + if flags&frameFlagKeepalive == 0 || flags&frameFlagServer == 0 { + t.Fatalf("expected keepalive+server flags, got %#x", flags) + } +} + +func TestFrameDirectionEnforced(t *testing.T) { + f := testFrameCrypto(t) + frame, err := f.seal(false, []byte("up"), false) + if err != nil { + t.Fatal(err) + } + if _, _, err := f.open(frame, true); err == nil { + t.Fatal("opening a client frame as server frame must fail") + } +} + +func TestFrameTamperDetection(t *testing.T) { + f := testFrameCrypto(t) + frame, err := f.seal(false, []byte("authenticated"), false) + if err != nil { + t.Fatal(err) + } + + // Tamper every header byte region: magic, version, flags, session, + // seq, payload length. + flips := []int{0, 3, 4, 5, 8, 15, 16, 19, 20, 21} + for _, i := range flips { + bad := make([]byte, len(frame)) + copy(bad, frame) + bad[i] ^= 0xFF + if _, _, err := f.open(bad, false); err == nil { + t.Fatalf("tampered byte %d was accepted", i) + } + } + + // Flip a payload byte (after the AAD region). + bad := make([]byte, len(frame)) + copy(bad, frame) + bad[len(bad)-1] ^= 0xFF + if _, _, err := f.open(bad, false); err == nil { + t.Fatal("tampered payload was accepted") + } + + // A truncated frame must be rejected. + if _, _, err := f.open(frame[:len(frame)-1], false); err == nil { + t.Fatal("truncated frame was accepted") + } +} + +func TestFrameReplayProtection(t *testing.T) { + f := testFrameCrypto(t) + + frame, err := f.seal(false, []byte("one"), false) + if err != nil { + t.Fatal(err) + } + if _, _, err := f.open(frame, false); err != nil { + t.Fatalf("first open: %v", err) + } + // Replaying the exact same frame must be rejected. + if _, _, err := f.open(frame, false); err == nil { + t.Fatal("replayed frame was accepted") + } + // Same seq, different ciphertext (attacker re-encrypt guess) must fail. + if _, _, err := f.open(frame, false); err == nil { + t.Fatal("replayed frame accepted twice") + } +} + +func TestFrameReorderingWithinWindow(t *testing.T) { + f := testFrameCrypto(t) + + var frames [][]byte + for i := 0; i < 10; i++ { + fr, err := f.seal(false, []byte{byte(i)}, false) + if err != nil { + t.Fatal(err) + } + frames = append(frames, fr) + } + // Deliver 0..9 in scrambled order: all must be accepted exactly once. + order := []int{2, 0, 1, 5, 3, 4, 9, 6, 7, 8} + for _, i := range order { + if _, _, err := f.open(frames[i], false); err != nil { + t.Fatalf("frame %d out of order rejected: %v", i, err) + } + } + // All frames are now consumed; resending any must be rejected. + for i := 0; i < 10; i++ { + if _, _, err := f.open(frames[i], false); err == nil { + t.Fatalf("replayed frame %d accepted", i) + } + } +} + +func TestFrameSeqJumpAdvance(t *testing.T) { + f := testFrameCrypto(t) + var first []byte + for i := 0; i < 70; i++ { + fr, err := f.seal(false, []byte{byte(i)}, false) + if err != nil { + t.Fatal(err) + } + if i == 0 { + first = fr + } + if _, _, err := f.open(fr, false); err != nil { + t.Fatalf("frame %d: %v", i, err) + } + } + // The window has advanced past seq 0 (base=69); replaying it must fail. + if _, _, err := f.open(first, false); err == nil { + t.Fatal("stale frame accepted after window advance") + } +} + +func TestFrameKeepaliveFlag(t *testing.T) { + f := testFrameCrypto(t) + frame, err := f.seal(false, nil, true) + if err != nil { + t.Fatal(err) + } + payload, flags, err := f.open(frame, false) + if err != nil { + t.Fatalf("open: %v", err) + } + if len(payload) != 0 { + t.Fatalf("keepalive payload must be empty, got %d bytes", len(payload)) + } + if flags&frameFlagKeepalive == 0 { + t.Fatal("keepalive flag not set") + } +} + +func TestFrameWrongKeyRejected(t *testing.T) { + a := testFrameCrypto(t) + b, err := newFrameCrypto([]byte("other-psk"), a.sid) + if err != nil { + t.Fatal(err) + } + frame, err := a.seal(false, []byte("secret"), false) + if err != nil { + t.Fatal(err) + } + if _, _, err := b.open(frame, false); err == nil { + t.Fatal("frame sealed with a different PSK was accepted") + } +} + +func TestSealSplit(t *testing.T) { + f := testFrameCrypto(t) + payload := bytes.Repeat([]byte("x"), frameMaxPayload*3+7) + + frames, err := f.sealSplit(false, payload, 0, false) + if err != nil { + t.Fatal(err) + } + if len(frames) != 4 { + t.Fatalf("expected 4 frames, got %d", len(frames)) + } + var got []byte + for _, fr := range frames { + pt, _, err := f.open(fr, false) + if err != nil { + t.Fatalf("open: %v", err) + } + got = append(got, pt...) + } + if !bytes.Equal(got, payload) { + t.Fatal("split payload mismatch") + } + + // Empty payload produces a single empty frame. + frames, err = f.sealSplit(false, nil, 0, true) + if err != nil { + t.Fatal(err) + } + if len(frames) != 1 { + t.Fatalf("expected 1 frame for empty payload, got %d", len(frames)) + } +} + +func TestReplayWindow(t *testing.T) { + var w replayWindow + if !w.accept(100) { + t.Fatal("first seq must be accepted") + } + if w.accept(100) { + t.Fatal("duplicate must be rejected") + } + if !w.accept(101) { + t.Fatal("next seq must be accepted") + } + // seq 99 is below the max but still inside the window and unseen: + // tolerated reordering. + if !w.accept(99) { + t.Fatal("in-window reordering must be accepted") + } + if w.accept(99) { + t.Fatal("duplicate in-window seq must be rejected") + } + if !w.accept(160) { + t.Fatal("seq jump must be accepted") + } + // seq 99 is now outside the window (base=160, window floor=97). + if w.accept(99) { + t.Fatal("seq below window floor must be rejected") + } + if w.accept(160) { + t.Fatal("duplicate after jump must be rejected") + } +} + +func TestFrameSessionID(t *testing.T) { + f := testFrameCrypto(t) + frame, err := f.seal(false, []byte("x"), false) + if err != nil { + t.Fatal(err) + } + sid, ok := frameSessionID(frame) + if !ok { + t.Fatal("frameSessionID failed on valid frame") + } + if sid != f.sid { + t.Fatal("session id mismatch") + } + // Non-frame traffic (e.g. a real TLS ClientHello) must not parse. + if _, ok := frameSessionID([]byte("not a frame")); ok { + t.Fatal("garbage accepted as frame") + } +} diff --git a/transport/internet/finalmask/rawpacket/masquerade.go b/transport/internet/finalmask/rawpacket/masquerade.go new file mode 100644 index 000000000000..4d3c497787d5 --- /dev/null +++ b/transport/internet/finalmask/rawpacket/masquerade.go @@ -0,0 +1,405 @@ +package rawpacket + +import ( + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/x509" + "crypto/x509/pkix" + "encoding/binary" + "log" + "math/big" + "net/netip" + "strings" + "sync" + "time" +) + +// masquerade answers probes that do not speak the tunnel protocol, so the +// relay port looks like a real service: +// +// http/tls: fake TCP handshake, then serve a static HTTP page or a +// TLS ServerHello + certificate flow +// dns: answer UDP queries with a DNS reply (A record for type A, +// NXDOMAIN otherwise), using the relay's own address +// +// Replies are sent from the address the probe dialed (dst of the +// incoming packet), never from the tunnel's spoofed source IPs. + +type masqueradeMode int + +const ( + masqOff masqueradeMode = iota + masqHTTP + masqTLS + masqDNS + + masqFlowTTL = 2 * time.Minute + masqFlowCap = 4096 + masqMaxChunkLen = 1400 +) + +func parseMasqueradeMode(s string) masqueradeMode { + switch strings.ToLower(strings.TrimSpace(s)) { + case "http": + return masqHTTP + case "tls", "https": + return masqTLS + case "dns": + return masqDNS + default: + return masqOff + } +} + +func (m masqueradeMode) String() string { + switch m { + case masqHTTP: + return "http" + case masqTLS: + return "tls" + case masqDNS: + return "dns" + default: + return "off" + } +} + +type masqKey struct { + ip netip.Addr + port uint16 +} + +type fakeFlow struct { + tcp *TCPSimState + resp []byte + sent int + lastSeen time.Time +} + +type masquerade struct { + mode masqueradeMode + fd *rawSendFD + relayP uint16 // relay listen port, source port of replies + + mu sync.Mutex + flows map[masqKey]*fakeFlow + ipID uint16 + idMu sync.Mutex + + httpResp []byte + tlsResp []byte + + done chan struct{} +} + +// newMasquerade builds the responder for mode; mode ""/"off" returns nil. +func newMasquerade(mode string, relayPort uint16) (*masquerade, error) { + m := parseMasqueradeMode(mode) + if m == masqOff { + return nil, nil + } + fd, err := openRawSenderAny() + if err != nil { + return nil, err + } + resp, err := masqueradeResponses(m) + if err != nil { + fd.close() + return nil, err + } + mg := &masquerade{ + mode: m, + fd: fd, + relayP: relayPort, + flows: make(map[masqKey]*fakeFlow), + httpResp: resp, + tlsResp: resp, + done: make(chan struct{}), + } + go mg.gcLoop() + log.Printf("[rawpacket] masquerade enabled: %s (port %d)", m, relayPort) + return mg, nil +} + +// masqueradeResponses builds the static response payload for the mode. +func masqueradeResponses(m masqueradeMode) ([]byte, error) { + switch m { + case masqHTTP: + return fakeHTTPResponse(), nil + case masqTLS: + return buildFakeTLSServer() + default: + return nil, nil + } +} + +func (m *masquerade) close() { + if m == nil { + return + } + close(m.done) + m.fd.close() +} + +func (m *masquerade) nextIPID() uint16 { + m.idMu.Lock() + defer m.idMu.Unlock() + m.ipID++ + return m.ipID +} + +// onTCPSYN handles a bare SYN from a probe: answer SYN|ACK and start a +// fake flow so subsequent data can be served. +func (m *masquerade) onTCPSYN(relayIP netip.Addr, relayPort uint16, probeIP netip.Addr, probePort uint16, seq uint32) { + if m == nil || (m.mode != masqHTTP && m.mode != masqTLS) { + return + } + key := masqKey{probeIP, probePort} + m.mu.Lock() + f := m.flows[key] + if f == nil { + resp := m.httpResp + if m.mode == masqTLS { + resp = m.tlsResp + } + f = &fakeFlow{tcp: newTCPSimState(), resp: resp} + if len(m.flows) < masqFlowCap { + m.flows[key] = f + } + } + f.lastSeen = time.Now() + f.tcp.observeClientSeq(seq, 0) + m.mu.Unlock() + m.sendTCP(relayIP, relayPort, probeIP, probePort, f, nil, true) +} + +// onTCPData serves the fake response to probe data. The response is +// streamed in MSS-sized chunks and repeats once exhausted, so repeated +// requests (e.g. a browser reloading) keep getting answers. +func (m *masquerade) onTCPData(relayIP netip.Addr, relayPort uint16, probeIP netip.Addr, probePort uint16, seq uint32, payload []byte) { + if m == nil || (m.mode != masqHTTP && m.mode != masqTLS) || len(payload) == 0 { + return + } + key := masqKey{probeIP, probePort} + m.mu.Lock() + f := m.flows[key] + if f == nil { + m.mu.Unlock() + return + } + f.lastSeen = time.Now() + f.tcp.observeClientSeq(seq, len(payload)) + chunk := f.resp[f.sent:] + if len(chunk) > masqMaxChunkLen { + chunk = chunk[:masqMaxChunkLen] + } + f.sent += len(chunk) + if f.sent >= len(f.resp) { + f.sent = 0 + } + m.mu.Unlock() + m.sendTCP(relayIP, relayPort, probeIP, probePort, f, chunk, false) +} + +func (m *masquerade) sendTCP(relayIP netip.Addr, relayPort uint16, probeIP netip.Addr, probePort uint16, f *fakeFlow, payload []byte, syn bool) { + var flags uint8 + if syn { + flags = TCPFlagSyn | TCPFlagAck + } else { + flags = TCPFlagAck + } + seq := f.tcp.nextSeq(len(payload)) + pkt := BuildTCPPacket(relayIP, probeIP, relayPort, probePort, seq, f.tcp.ack(), flags, payload, 64, m.nextIPID(), false) + _ = m.fd.sendTo(pkt, probeIP) +} + +// onUDP answers a probe datagram with a fake DNS reply. +func (m *masquerade) onUDP(relayIP netip.Addr, relayPort uint16, probeIP netip.Addr, probePort uint16, payload []byte) { + if m == nil || m.mode != masqDNS || len(payload) < 12 { + return + } + reply := fakeDNSReply(payload, relayIP) + if len(reply) == 0 { + return + } + pkt := BuildRawUDP(relayIP, probeIP, relayPort, probePort, reply, 64, m.nextIPID()) + _ = m.fd.sendTo(pkt, probeIP) +} + +// gcLoop drops stale fake flows. +func (m *masquerade) gcLoop() { + t := time.NewTicker(30 * time.Second) + defer t.Stop() + for { + select { + case <-m.done: + return + case <-t.C: + now := time.Now() + m.mu.Lock() + for k, f := range m.flows { + if now.Sub(f.lastSeen) > masqFlowTTL { + delete(m.flows, k) + } + } + m.mu.Unlock() + } + } +} + +// fakeHTTPResponse is a minimal nginx-style page. +func fakeHTTPResponse() []byte { + body := "\r\nWelcome to nginx!\r\n\r\n

Welcome to nginx!

\r\n\r\n\r\n" + hdr := "HTTP/1.1 200 OK\r\nServer: nginx\r\nContent-Type: text/html\r\nContent-Length: " + itoa(len(body)) + "\r\nConnection: close\r\n\r\n" + return append([]byte(hdr), body...) +} + +func itoa(n int) string { + if n == 0 { + return "0" + } + var b [16]byte + i := len(b) + for n > 0 { + i-- + b[i] = byte('0' + n%10) + n /= 10 + } + return string(b[i:]) +} + +// buildFakeTLSServer produces a canned TLS 1.2 ServerHello + Certificate + +// ServerHelloDone record flow backed by a self-signed ECDSA certificate. +// The handshake never completes (no key exchange), which is enough for +// passive DPI classification and port scanners. +func buildFakeTLSServer() ([]byte, error) { + key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + return nil, err + } + tmpl := &x509.Certificate{ + SerialNumber: big.NewInt(1), + Subject: pkix.Name{CommonName: "nginx", Organization: []string{"nginx"}}, + NotBefore: time.Now().Add(-24 * time.Hour), + NotAfter: time.Now().Add(365 * 24 * time.Hour), + KeyUsage: x509.KeyUsageDigitalSignature, + ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, + } + der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key) + if err != nil { + return nil, err + } + + var random [32]byte + _, _ = rand.Read(random[:]) + + // ServerHello (TLS 1.2, ECDHE_ECDSA_WITH_AES_128_GCM_SHA256) + sh := make([]byte, 0, 38+32) + sh = append(sh, 0x03, 0x03) + sh = append(sh, random[:]...) + sh = append(sh, 0x20) + sh = append(sh, random[:32]...) + sh = append(sh, 0xC0, 0x2B, 0x00) + + // handshake wrapper: type + 24-bit length + hello := tlsHandshakeRecord(0x02, sh) + + // Certificate + certMsg := make([]byte, 0, 3+len(der)) + certMsg = binary.BigEndian.AppendUint32(certMsg, uint32(len(der)))[1:] + certMsg = append(certMsg, der...) + cert := tlsHandshakeRecord(0x0B, certMsg) + + // ServerHelloDone + done := tlsHandshakeRecord(0x0E, nil) + + var out []byte + out = append(out, hello...) + out = append(out, cert...) + out = append(out, done...) + return out, nil +} + +// tlsHandshakeRecord wraps a handshake message in a TLS record (content +// type 0x16) with a 24-bit handshake length header. +func tlsHandshakeRecord(msgType byte, body []byte) []byte { + out := make([]byte, 0, 5+4+len(body)) + out = append(out, 0x16, 0x03, 0x03) + l := 4 + len(body) + out = append(out, byte(l>>8), byte(l)) + out = append(out, msgType) + out = append(out, byte(len(body)>>16), byte(len(body)>>8), byte(len(body))) + out = append(out, body...) + return out +} + +// fakeDNSReply builds a DNS reply for query: an A record with the relay's +// address for type A queries, NXDOMAIN otherwise. Malformed queries yield +// nil (no reply). The question is always echoed. +func fakeDNSReply(query []byte, relayIP netip.Addr) []byte { + if len(query) < 12 { + return nil + } + id := query[0:2] + flags := binary.BigEndian.Uint16(query[2:4]) + qd := binary.BigEndian.Uint16(query[4:6]) + if qd == 0 { + return nil + } + off := 12 + qnameEnd := -1 + for off < len(query) { + l := int(query[off]) + if l == 0 { + off++ + qnameEnd = off + break + } + if l&0xC0 == 0xC0 { // compression pointer: name ends at 2-byte pointer + off += 2 + qnameEnd = off + break + } + if off+1+l > len(query) { + return nil + } + off += 1 + l + if off-12 > 255 { + return nil + } + } + if qnameEnd < 0 || off+4 > len(query) { + return nil + } + qtype := binary.BigEndian.Uint16(query[off:]) + qclass := binary.BigEndian.Uint16(query[off+2:]) + + // QR=1, opcode echoed, RD echoed, RA=1; rcode 3 (NXDOMAIN) unless we + // answer the query. + rcode := uint16(3) + ancount := uint16(0) + var answer []byte + if qtype == 1 && qclass == 1 && relayIP.Is4() { // A query + rcode = 0 + ancount = 1 + answer = make([]byte, 0, 16) + answer = append(answer, 0xC0, 0x0C) // name pointer to question + answer = binary.BigEndian.AppendUint16(answer, 1) // type A + answer = binary.BigEndian.AppendUint16(answer, 1) // class IN + answer = binary.BigEndian.AppendUint32(answer, 60) // TTL + answer = binary.BigEndian.AppendUint16(answer, 4) // rdlength + answer = append(answer, relayIP.AsSlice()...) + } + + reply := make([]byte, 0, len(query)+16) + reply = append(reply, id...) + reply = binary.BigEndian.AppendUint16(reply, 0x8000|(flags&0x7800)|0x0080|rcode) + reply = binary.BigEndian.AppendUint16(reply, 1) // QDCOUNT + reply = binary.BigEndian.AppendUint16(reply, ancount) + reply = binary.BigEndian.AppendUint16(reply, 0) // NS + reply = binary.BigEndian.AppendUint16(reply, 0) // AR + reply = append(reply, query[12:off+4]...) // question: qname + type + class + reply = append(reply, answer...) + return reply +} diff --git a/transport/internet/finalmask/rawpacket/masquerade_test.go b/transport/internet/finalmask/rawpacket/masquerade_test.go new file mode 100644 index 000000000000..42d233280377 --- /dev/null +++ b/transport/internet/finalmask/rawpacket/masquerade_test.go @@ -0,0 +1,301 @@ +package rawpacket + +import ( + "encoding/binary" + "net/netip" + "testing" +) + +func TestParseMasqueradeMode(t *testing.T) { + cases := map[string]masqueradeMode{ + "": masqOff, + "off": masqOff, + "http": masqHTTP, + "tls": masqTLS, + "https": masqTLS, + "dns": masqDNS, + "HTTP": masqHTTP, + } + for in, want := range cases { + if got := parseMasqueradeMode(in); got != want { + t.Fatalf("parseMasqueradeMode(%q) = %v, want %v", in, got, want) + } + } +} + +func TestFakeHTTPResponse(t *testing.T) { + resp := fakeHTTPResponse() + if len(resp) == 0 { + t.Fatal("empty HTTP response") + } + s := string(resp) + if !startsWith(s, "HTTP/1.1 200 OK\r\n") { + t.Fatalf("missing status line: %q", s[:32]) + } + // Content-Length must match the body length + body := "\r\nWelcome to nginx!\r\n\r\n

Welcome to nginx!

\r\n\r\n\r\n" + cl := "Content-Length: " + itoa(len(body)) + if !contains(s, cl) { + t.Fatalf("missing %q in %q", cl, s[:120]) + } +} + +func TestBuildFakeTLSServer(t *testing.T) { + resp, err := buildFakeTLSServer() + if err != nil { + t.Fatal(err) + } + // Expect 3 TLS records: ServerHello, Certificate, ServerHelloDone + var off int + var types []byte + var lens []int + for off < len(resp) && len(types) < 3 { + if off+5 > len(resp) || resp[off] != 0x16 { + t.Fatalf("bad record header at %d: %x", off, resp[off:]) + } + l := int(resp[off+3])<<8 | int(resp[off+4]) + if off+5+l > len(resp) { + t.Fatalf("record overruns buffer at %d", off) + } + types = append(types, resp[off+5]) + lens = append(lens, l) + off += 5 + l + } + if off != len(resp) { + t.Fatalf("trailing bytes after 3 records: %d", len(resp)-off) + } + if types[0] != 0x02 || types[1] != 0x0B || types[2] != 0x0E { + t.Fatalf("record types = %x, want [2 b e]", types) + } + // Certificate record must contain a DER cert + if lens[1] < 4 { + t.Fatalf("certificate record too small: %d", lens[1]) + } +} + +func TestFakeDNSReplyA(t *testing.T) { + // build a DNS A query for example.com + q := buildDNSQuery("example.com", 1, 0x1234, 0x0100) + relay := netip.MustParseAddr("203.0.113.9") + reply := fakeDNSReply(q, relay) + if reply == nil { + t.Fatal("nil reply for A query") + } + if binary.BigEndian.Uint16(reply[0:2]) != 0x1234 { + t.Fatalf("bad ID") + } + flags := binary.BigEndian.Uint16(reply[2:4]) + if flags&0x8000 == 0 { + t.Fatal("QR not set") + } + if flags&0x000F != 0 { + t.Fatalf("rcode = %d, want 0 for A query", flags&0x000F) + } + if binary.BigEndian.Uint16(reply[4:6]) != 1 { + t.Fatalf("QDCOUNT = %d, want 1", binary.BigEndian.Uint16(reply[4:6])) + } + if an := binary.BigEndian.Uint16(reply[6:8]); an != 1 { + t.Fatalf("ANCOUNT = %d, want 1", an) + } + // answer: pointer to name + A record with relay IP + a := reply[len(reply)-4:] + if a[0] != 203 || a[3] != 9 { + t.Fatalf("answer = %v, want relay IP", a) + } + if rdlen := binary.BigEndian.Uint16(reply[len(reply)-6 : len(reply)-4]); rdlen != 4 { + t.Fatalf("rdlength = %d, want 4", rdlen) + } +} + +func TestFakeDNSReplyNXDOMAIN(t *testing.T) { + q := buildDNSQuery("host.example", 28, 0xABCD, 0x0100) // AAAA query + relay := netip.MustParseAddr("203.0.113.9") + reply := fakeDNSReply(q, relay) + if reply == nil { + t.Fatal("nil reply") + } + if flags := binary.BigEndian.Uint16(reply[2:4]); flags&0x000F != 3 { + t.Fatalf("rcode = %d, want 3 (NXDOMAIN)", flags&0x000F) + } + if an := binary.BigEndian.Uint16(reply[6:8]); an != 0 { + t.Fatalf("ANCOUNT = %d, want 0", an) + } +} + +func TestFakeDNSReplyMalformed(t *testing.T) { + relay := netip.MustParseAddr("203.0.113.9") + if fakeDNSReply([]byte("short"), relay) != nil { + t.Fatal("short query should be dropped") + } + // QDCOUNT = 0 + q := make([]byte, 12) + if fakeDNSReply(q, relay) != nil { + t.Fatal("zero-question query should be dropped") + } + // truncated name + q = buildDNSQuery("example.com", 1, 0x1, 0x0100) + if fakeDNSReply(q[:len(q)-4], relay) != nil { + t.Fatal("truncated query should be dropped") + } +} + +func TestMasqueradeFlowLifecycle(t *testing.T) { + // build directly to avoid opening a raw socket (needs privileges) + rec := &recordingFD{} + m := &masquerade{ + mode: masqHTTP, + fd: rec.fd(), + relayP: 443, + flows: make(map[masqKey]*fakeFlow), + httpResp: fakeHTTPResponse(), + done: make(chan struct{}), + } + defer close(m.done) + + probe := netip.MustParseAddr("198.51.100.7") + relay := netip.MustParseAddr("203.0.113.9") + + // bare SYN + m.onTCPSYN(relay, 443, probe, 50000, 1000) + if len(rec.pkts) != 1 { + t.Fatalf("SYN should produce 1 packet, got %d", len(rec.pkts)) + } + synack := rec.pkts[0] + if synack[33] != TCPFlagSyn|TCPFlagAck { + t.Fatalf("flags = %#x, want SYN|ACK", synack[33]) + } + if ack := binary.BigEndian.Uint32(synack[28:32]); ack != 1001 { + t.Fatalf("ack = %d, want 1001", ack) + } + if binary.BigEndian.Uint16(synack[20:22]) != 443 { + t.Fatalf("src port = %d, want 443", binary.BigEndian.Uint16(synack[20:22])) + } + + // data (HTTP GET) -> response chunk + rec.pkts = nil + m.onTCPData(relay, 443, probe, 50000, 1001, []byte("GET / HTTP/1.1\r\n\r\n")) + if len(rec.pkts) != 1 { + t.Fatalf("data should produce 1 packet, got %d", len(rec.pkts)) + } + data := rec.pkts[0] + payload := data[52:] // 20 ip + 32 tcp (20 hdr + 12 options) + if !startsWith(string(payload), "HTTP/1.1 200 OK") { + t.Fatalf("unexpected payload: %q", payload[:min(len(payload), 40)]) + } + if seq := binary.BigEndian.Uint32(data[24:28]); seq == 0 { + t.Fatal("seq should be relay ISN, got 0") + } + + // unknown flow data -> no reply + rec.pkts = nil + m.onTCPData(relay, 443, netip.MustParseAddr("198.51.100.8"), 51000, 1, []byte("x")) + if len(rec.pkts) != 0 { + t.Fatalf("unknown flow should not get a reply") + } +} + +func TestMasqueradeDNSFlow(t *testing.T) { + rec := &recordingFD{} + m := &masquerade{ + mode: masqDNS, + fd: rec.fd(), + relayP: 53, + flows: make(map[masqKey]*fakeFlow), + done: make(chan struct{}), + } + defer close(m.done) + + probe := netip.MustParseAddr("198.51.100.7") + relay := netip.MustParseAddr("203.0.113.9") + q := buildDNSQuery("example.com", 1, 0x4242, 0x0100) + m.onUDP(relay, 53, probe, 40000, q) + if len(rec.pkts) != 1 { + t.Fatalf("dns probe should get 1 reply, got %d", len(rec.pkts)) + } + pkt := rec.pkts[0] + if pkt[9] != 17 { + t.Fatalf("protocol = %d, want UDP", pkt[9]) + } + if binary.BigEndian.Uint16(pkt[22:24]) != 40000 { + t.Fatalf("dst port = %d, want 40000", binary.BigEndian.Uint16(pkt[22:24])) + } + udpPayload := pkt[28:] + // DNS reply parses + if len(udpPayload) < 12 || binary.BigEndian.Uint16(udpPayload[0:2]) != 0x4242 { + t.Fatalf("bad DNS reply in packet") + } + + // non-DNS garbage -> no reply + rec.pkts = nil + m.onUDP(relay, 53, probe, 40000, []byte("garbage")) + if len(rec.pkts) != 0 { + t.Fatalf("garbage should not get a DNS reply") + } +} + +func TestMasqueradeOff(t *testing.T) { + m, err := newMasquerade("", 443) + if err != nil || m != nil { + t.Fatalf("off mode should return nil, nil; got %v, %v", m, err) + } + m, err = newMasquerade("off", 443) + if err != nil || m != nil { + t.Fatalf("off mode should return nil, nil; got %v, %v", m, err) + } +} + +// --- helpers --- + +type recordingFD struct { + pkts [][]byte +} + +func (r *recordingFD) fd() *rawSendFD { + rf := &rawSendFD{} + rf.sendFn = func(pkt []byte, _ netip.Addr) error { + r.pkts = append(r.pkts, append([]byte(nil), pkt...)) + return nil + } + return rf +} + +func buildDNSQuery(name string, qtype uint16, id uint16, flags uint16) []byte { + q := make([]byte, 12) + binary.BigEndian.PutUint16(q[0:], id) + binary.BigEndian.PutUint16(q[2:], flags) + binary.BigEndian.PutUint16(q[4:], 1) + for _, part := range stringsSplit(name, ".") { + q = append(q, byte(len(part))) + q = append(q, part...) + } + q = append(q, 0) + q = binary.BigEndian.AppendUint16(q, qtype) + q = binary.BigEndian.AppendUint16(q, 1) + return q +} + +func stringsSplit(s, sep string) []string { + var out []string + start := 0 + for i := 0; i+len(sep) <= len(s); i++ { + if s[i:i+len(sep)] == sep { + out = append(out, s[start:i]) + start = i + len(sep) + } + } + out = append(out, s[start:]) + return out +} + +func startsWith(s, prefix string) bool { + return len(s) >= len(prefix) && s[:len(prefix)] == prefix +} + +func contains(s, sub string) bool { + for i := 0; i+len(sub) <= len(s); i++ { + if s[i:i+len(sub)] == sub { + return true + } + } + return false +} diff --git a/transport/internet/finalmask/rawpacket/platform.go b/transport/internet/finalmask/rawpacket/platform.go new file mode 100644 index 000000000000..34a3a855dea4 --- /dev/null +++ b/transport/internet/finalmask/rawpacket/platform.go @@ -0,0 +1,5 @@ +//go:build darwin || freebsd || linux || (windows && (amd64 || 386)) + +package rawpacket + +const PlatformSupported = true diff --git a/transport/internet/finalmask/rawpacket/platform_unsupported.go b/transport/internet/finalmask/rawpacket/platform_unsupported.go new file mode 100644 index 000000000000..5ef3145901aa --- /dev/null +++ b/transport/internet/finalmask/rawpacket/platform_unsupported.go @@ -0,0 +1,5 @@ +//go:build !darwin && !freebsd && !linux && !(windows && (amd64 || 386)) + +package rawpacket + +const PlatformSupported = false diff --git a/transport/internet/finalmask/rawpacket/spoof_bpf_linux.go b/transport/internet/finalmask/rawpacket/spoof_bpf_linux.go new file mode 100644 index 000000000000..4669618468ed --- /dev/null +++ b/transport/internet/finalmask/rawpacket/spoof_bpf_linux.go @@ -0,0 +1,53 @@ +//go:build linux + +package rawpacket + +import ( + "log" + "unsafe" + + "golang.org/x/sys/unix" +) + +// sockFilter and sockFprog mirror the kernel's struct sock_filter / +// struct sock_fprog (classic BPF). SO_ATTACH_FILTER is a Linux-only +// socket option; other platforms build the stub below. +type sockFilter struct { + Code uint16 + Jt uint8 + Jf uint8 + K uint32 +} + +type sockFprog struct { + Len uint16 + Filter *sockFilter +} + +const ( + bpfLdAbs = 0x30 // BPF_LD|BPF_B|BPF_ABS: load byte at absolute offset + bpfJeq = 0x15 // BPF_JMP|BPF_JEQ|BPF_K + bpfRet = 0x06 // BPF_RET|BPF_K + bpfKeepAll = 0xffffffff + bpfDrop = 0 + soAttachFilter = 26 // SOL_SOCKET level option (Linux) +) + +// attachBPFFilter installs a filter that keeps only IPv4 packets whose +// protocol byte (offset 9) matches proto, dropping everything else in +// the kernel. Failures are logged but non-fatal: userspace already +// filters by protocol. +func attachBPFFilter(fd int, proto uint8) { + filter := []sockFilter{ + {Code: bpfLdAbs, K: 9}, // A = ip.proto + {Code: bpfJeq, Jt: 1, Jf: 0, K: uint32(proto)}, // if A == proto skip the drop + {Code: bpfRet, K: bpfDrop}, // else drop + {Code: bpfRet, K: bpfKeepAll}, // keep + } + fprog := sockFprog{Len: uint16(len(filter)), Filter: &filter[0]} + _, _, errno := unix.Syscall6(unix.SYS_SETSOCKOPT, uintptr(fd), uintptr(unix.SOL_SOCKET), uintptr(soAttachFilter), + uintptr(unsafe.Pointer(&fprog)), unsafe.Sizeof(fprog), 0) + if errno != 0 { + log.Printf("[rawpacket] failed to attach BPF filter (proto %d): %v", proto, errno) + } +} diff --git a/transport/internet/finalmask/rawpacket/spoof_bpf_stub.go b/transport/internet/finalmask/rawpacket/spoof_bpf_stub.go new file mode 100644 index 000000000000..3bc6b70d762f --- /dev/null +++ b/transport/internet/finalmask/rawpacket/spoof_bpf_stub.go @@ -0,0 +1,7 @@ +//go:build !linux + +package rawpacket + +// attachBPFFilter is a no-op on platforms without SO_ATTACH_FILTER +// (darwin/freebsd raw sockets do not support classic-BPF attachment). +func attachBPFFilter(fd int, proto uint8) {} diff --git a/transport/internet/finalmask/rawpacket/spoof_conn.go b/transport/internet/finalmask/rawpacket/spoof_conn.go new file mode 100644 index 000000000000..b0d72b9c91d8 --- /dev/null +++ b/transport/internet/finalmask/rawpacket/spoof_conn.go @@ -0,0 +1,240 @@ +package rawpacket + +import ( + "errors" + "fmt" + "net" + "net/netip" + "os" + "sync" + "sync/atomic" + "time" +) + +// dialCounter round-robins the spoof source IP across connections so each +// session uses exactly one source address (per-session rotation instead of +// per-packet). This keeps the relay's (sessionID -> client address) +// mapping stable. +var dialCounter atomic.Uint64 + +type SpoofConn struct { + sid [8]byte + crypto *frameCrypto + sender SpoofSender + tcp *TCPSimState + demux *frameDemux + recvCh chan demuxData + relayIP netip.Addr + relayP uint16 + + maxPayload int + + writeMu sync.Mutex + + keepaliveStop chan struct{} + closeOnce sync.Once + + readDeadline atomic.Int64 // unixNano, 0 = none + writeDeadline atomic.Int64 +} + +func DialSpoof(relayAddr netip.AddrPort, spoofIPs []netip.Addr, srcPort uint16, ttl uint8, mtu uint32, sendProto, recvProto string, peerSpoofIP netip.Addr, psk []byte) (net.Conn, error) { + if len(psk) == 0 { + return nil, errors.New("rawpacket: auth (PSK) required in local mode") + } + if len(spoofIPs) == 0 { + return nil, errors.New("rawpacket: at least one spoof IP required") + } + if sendProto == "" { + sendProto = "tcp" + } + if recvProto == "" { + recvProto = "udp" + } + + if recvProto == "icmp" || recvProto == "icmpv6" { + suppressICMPEchoReply() + } + + sid, err := newSessionID() + if err != nil { + return nil, fmt.Errorf("rawpacket: session id: %w", err) + } + crypto, err := newFrameCrypto(psk, sid) + if err != nil { + return nil, fmt.Errorf("rawpacket: frame crypto: %w", err) + } + + // One source IP per session: per-session rotation. + srcIP := spoofIPs[dialCounter.Add(1)%uint64(len(spoofIPs))] + sender, err := NewSender(sendProto, &SpoofSenderConfig{ + SourceIPs: []netip.Addr{srcIP}, + SourcePort: srcPort, + TTL: ttl, + }) + if err != nil { + return nil, fmt.Errorf("rawpacket: create sender: %w", err) + } + + demux := getFrameDemux(recvProto, srcPort, peerSpoofIP) + recvCh := make(chan demuxData, 64) + if err := demux.register(sid, crypto, recvCh); err != nil { + sender.Close() + return nil, fmt.Errorf("rawpacket: create receiver: %w", err) + } + + c := &SpoofConn{ + sid: sid, + crypto: crypto, + sender: sender, + tcp: newTCPSimState(), + demux: demux, + recvCh: recvCh, + relayIP: relayAddr.Addr(), + relayP: relayAddr.Port(), + maxPayload: maxPayloadForMTU(mtu), + keepaliveStop: make(chan struct{}), + } + go c.keepaliveLoop() + return c, nil +} + +// maxPayloadForMTU bounds the frame payload so the largest possible wire +// packet (IPv4 + TCP with options + frame overhead) stays within mtu. +func maxPayloadForMTU(mtu uint32) int { + if mtu == 0 { + return frameMaxPayload + } + p := int(mtu) - 20 - 40 - frameOverhead + if p < 1 { + p = 1 + } + if p > frameMaxPayload { + p = frameMaxPayload + } + return p +} + +func (c *SpoofConn) Write(b []byte) (int, error) { + if len(b) == 0 { + return 0, nil + } + if dl := c.writeDeadline.Load(); dl != 0 { + if time.Now().UnixNano() >= dl { + return 0, os.ErrDeadlineExceeded + } + } + c.writeMu.Lock() + defer c.writeMu.Unlock() + + written := 0 + for len(b) > 0 { + chunk := b + if len(chunk) > c.maxPayload { + chunk = chunk[:c.maxPayload] + } + frame, err := c.crypto.seal(false, chunk, false) + if err != nil { + return written, err + } + if err := c.sender.Send(frame, c.relayIP, c.relayP, c.tcp); err != nil { + return written, err + } + written += len(chunk) + b = b[len(chunk):] + } + return written, nil +} + +func (c *SpoofConn) Read(buf []byte) (int, error) { + dl := c.readDeadline.Load() + if dl != 0 && time.Now().UnixNano() >= dl { + return 0, os.ErrDeadlineExceeded + } + + var timer *time.Timer + var timeout <-chan time.Time + if dl != 0 { + timer = time.NewTimer(time.Until(time.Unix(0, dl))) + timeout = timer.C + defer timer.Stop() + } + + select { + case data, ok := <-c.recvCh: + if !ok { + return 0, errors.New("rawpacket: connection closed") + } + if data.tcp != nil && data.tcp.Flags != 0 { + c.tcp.observePeer(data.tcp.Seq, len(data.payload)) + } + return copy(buf, data.payload), nil + case <-timeout: + return 0, os.ErrDeadlineExceeded + } +} + +// keepaliveLoop keeps the relay session alive during idle periods so the +// relay's garbage collector does not reap an idle but healthy connection. +func (c *SpoofConn) keepaliveLoop() { + t := time.NewTicker(25 * time.Second) + defer t.Stop() + for { + select { + case <-c.keepaliveStop: + return + case <-t.C: + c.writeMu.Lock() + frame, err := c.crypto.seal(false, nil, true) + if err == nil { + _ = c.sender.Send(frame, c.relayIP, c.relayP, c.tcp) + } + c.writeMu.Unlock() + } + } +} + +func (c *SpoofConn) Close() error { + c.closeOnce.Do(func() { + close(c.keepaliveStop) + c.demux.unregister(c.sid) + c.sender.Close() + }) + return nil +} + +func (c *SpoofConn) LocalAddr() net.Addr { + return &net.TCPAddr{IP: net.IPv4(0, 0, 0, 0), Port: 0} +} + +func (c *SpoofConn) RemoteAddr() net.Addr { + return &net.TCPAddr{IP: c.relayIP.AsSlice(), Port: int(c.relayP)} +} + +func setDeadline(d *atomic.Int64, t time.Time) error { + if t.IsZero() { + d.Store(0) + return nil + } + d.Store(t.UnixNano()) + return nil +} + +func (c *SpoofConn) SetDeadline(t time.Time) error { + if err := setDeadline(&c.readDeadline, t); err != nil { + return err + } + return setDeadline(&c.writeDeadline, t) +} + +func (c *SpoofConn) SetReadDeadline(t time.Time) error { + return setDeadline(&c.readDeadline, t) +} + +func (c *SpoofConn) SetWriteDeadline(t time.Time) error { + return setDeadline(&c.writeDeadline, t) +} + +func (c *SpoofConn) TcpMaskConn() {} +func (c *SpoofConn) RawConn() net.Conn { return nil } +func (c *SpoofConn) Splice() bool { return false } diff --git a/transport/internet/finalmask/rawpacket/spoof_icmp_utils.go b/transport/internet/finalmask/rawpacket/spoof_icmp_utils.go new file mode 100644 index 000000000000..3b14f7681dbb --- /dev/null +++ b/transport/internet/finalmask/rawpacket/spoof_icmp_utils.go @@ -0,0 +1,48 @@ +package rawpacket + +import ( + "log" + "os/exec" + "runtime" +) + +func suppressICMPEchoReply() bool { + switch runtime.GOOS { + case "linux": + err := exec.Command("sysctl", "-w", "net.ipv4.icmp_echo_ignore_all=1").Run() + if err != nil { + log.Printf("[rawpacket] failed to suppress ICMP echo replies: %v", err) + return false + } + log.Printf("[rawpacket] suppressed kernel ICMP echo replies") + return true + case "freebsd", "openbsd": + err := exec.Command("sysctl", "net.inet.icmp.bmcastecho=0").Run() + if err != nil { + log.Printf("[rawpacket] failed to suppress ICMP echo replies on %s: %v", runtime.GOOS, err) + return false + } + log.Printf("[rawpacket] suppressed kernel ICMP echo replies on %s", runtime.GOOS) + return true + default: + log.Printf("[rawpacket] ICMP echo reply suppression not supported on %s", runtime.GOOS) + return false + } +} + +func restoreICMPEchoReply() { + switch runtime.GOOS { + case "linux": + err := exec.Command("sysctl", "-w", "net.ipv4.icmp_echo_ignore_all=0").Run() + if err != nil { + log.Printf("[rawpacket] failed to restore ICMP echo replies: %v", err) + return + } + log.Printf("[rawpacket] restored kernel ICMP echo replies") + case "freebsd", "openbsd": + err := exec.Command("sysctl", "net.inet.icmp.bmcastecho=1").Run() + if err != nil { + log.Printf("[rawpacket] failed to restore ICMP echo replies on %s: %v", runtime.GOOS, err) + } + } +} diff --git a/transport/internet/finalmask/rawpacket/spoof_ip.go b/transport/internet/finalmask/rawpacket/spoof_ip.go new file mode 100644 index 000000000000..505601372142 --- /dev/null +++ b/transport/internet/finalmask/rawpacket/spoof_ip.go @@ -0,0 +1,75 @@ +package rawpacket + +import ( + "encoding/binary" + "net/netip" +) + +// BuildIPv4Header builds a 20-byte IPv4 header. df sets the Don't +// Fragment bit (real hosts set it; prevents MTU-blackhole fragmentation). +func BuildIPv4Header(totalLen uint16, id uint16, ttl uint8, protocol uint8, src, dst netip.Addr, df bool) []byte { + b := make([]byte, 20) + b[0] = (4 << 4) | 5 + b[1] = 0 + binary.BigEndian.PutUint16(b[2:], totalLen) + binary.BigEndian.PutUint16(b[4:], id) + if df { + binary.BigEndian.PutUint16(b[6:], 0x4000) + } else { + binary.BigEndian.PutUint16(b[6:], 0) + } + b[8] = ttl + b[9] = protocol + copy(b[12:16], src.AsSlice()) + copy(b[16:20], dst.AsSlice()) + csum := Checksum(b[:20], 0) + binary.BigEndian.PutUint16(b[10:], ^csum) + return b +} + +func BuildIPv6Header(payloadLen uint16, transportProtocol uint8, hopLimit uint8, src, dst netip.Addr) []byte { + b := make([]byte, 40) + binary.BigEndian.PutUint32(b[0:], 6<<28) + binary.BigEndian.PutUint16(b[4:], payloadLen) + b[6] = transportProtocol + b[7] = hopLimit + copy(b[8:24], src.AsSlice()) + copy(b[24:40], dst.AsSlice()) + return b +} + +func IPv4PseudoHeaderChecksum(src, dst netip.Addr, protocol uint8, tcpLen uint16) uint16 { + var csum uint32 + srcB := src.As4() + dstB := dst.As4() + for i := 0; i < 4; i += 2 { + csum += uint32(binary.BigEndian.Uint16(srcB[i:])) + } + for i := 0; i < 4; i += 2 { + csum += uint32(binary.BigEndian.Uint16(dstB[i:])) + } + csum += uint32(protocol) + csum += uint32(tcpLen) + for csum > 0xffff { + csum = (csum >> 16) + (csum & 0xffff) + } + return uint16(csum) +} + +func IPv6PseudoHeaderChecksum(src, dst netip.Addr, protocol uint8, totalLen uint32) uint16 { + var csum uint32 + srcB := src.As16() + dstB := dst.As16() + for i := 0; i < 16; i += 2 { + csum += uint32(binary.BigEndian.Uint16(srcB[i:])) + } + for i := 0; i < 16; i += 2 { + csum += uint32(binary.BigEndian.Uint16(dstB[i:])) + } + csum += uint32(protocol) + csum += totalLen + for csum > 0xffff { + csum = (csum >> 16) + (csum & 0xffff) + } + return uint16(csum) +} diff --git a/transport/internet/finalmask/rawpacket/spoof_rawsend.go b/transport/internet/finalmask/rawpacket/spoof_rawsend.go new file mode 100644 index 000000000000..1c10faef91b0 --- /dev/null +++ b/transport/internet/finalmask/rawpacket/spoof_rawsend.go @@ -0,0 +1,93 @@ +//go:build darwin || freebsd || linux + +package rawpacket + +import ( + "fmt" + "net/netip" + "sync" + + "golang.org/x/sys/unix" +) + +type rawSendFD struct { + fd int + sockAddr unix.Sockaddr + // sendFn, when set, replaces the real send path (used by tests). + sendFn func(pkt []byte, dstIP netip.Addr) error + mu sync.Mutex + closed bool +} + +func openRawSender(dstIP netip.Addr) (*rawSendFD, error) { + if !dstIP.Is4() { + return nil, fmt.Errorf("rawpacket: IPv6 raw sender not yet supported") + } + + fd, err := openRawSenderAny() + if err != nil { + return nil, err + } + sa := &unix.SockaddrInet4{} + sa.Addr = dstIP.As4() + fd.sockAddr = sa + return fd, nil +} + +// openRawSenderAny opens a raw sending socket without binding it to a +// fixed destination. Used by the masquerade responder, which must send +// to arbitrary probe addresses. +func openRawSenderAny() (*rawSendFD, error) { + fd, err := unix.Socket(unix.AF_INET, unix.SOCK_RAW, unix.IPPROTO_RAW) + if err != nil { + return nil, fmt.Errorf("rawpacket: open SOCK_RAW: %w", err) + } + err = unix.SetsockoptInt(fd, unix.IPPROTO_IP, unix.IP_HDRINCL, 1) + if err != nil { + unix.Close(fd) + return nil, fmt.Errorf("rawpacket: set IP_HDRINCL: %w", err) + } + + _ = unix.SetsockoptInt(fd, unix.SOL_SOCKET, unix.SO_SNDBUF, 4*1024*1024) + return &rawSendFD{fd: fd}, nil +} + +func (r *rawSendFD) send(packet []byte) error { + r.mu.Lock() + defer r.mu.Unlock() + if r.closed { + return fmt.Errorf("rawpacket: raw sender closed") + } + if r.sockAddr == nil { + return fmt.Errorf("rawpacket: raw sender has no destination") + } + return unix.Sendto(r.fd, packet, 0, r.sockAddr) +} + +// sendTo sends packet to dstIP, building the socket address per call. +func (r *rawSendFD) sendTo(packet []byte, dstIP netip.Addr) error { + if r.sendFn != nil { + return r.sendFn(packet, dstIP) + } + if !dstIP.Is4() { + return fmt.Errorf("rawpacket: IPv6 raw sender not yet supported") + } + r.mu.Lock() + defer r.mu.Unlock() + if r.closed { + return fmt.Errorf("rawpacket: raw sender closed") + } + sa := &unix.SockaddrInet4{} + sa.Addr = dstIP.As4() + return unix.Sendto(r.fd, packet, 0, sa) +} + +func (r *rawSendFD) close() error { + r.mu.Lock() + defer r.mu.Unlock() + if r.closed { + return nil + } + r.closed = true + return unix.Close(r.fd) +} diff --git a/transport/internet/finalmask/rawpacket/spoof_rawsend_stub.go b/transport/internet/finalmask/rawpacket/spoof_rawsend_stub.go new file mode 100644 index 000000000000..1d59e4cfc6e6 --- /dev/null +++ b/transport/internet/finalmask/rawpacket/spoof_rawsend_stub.go @@ -0,0 +1,30 @@ +//go:build !darwin && !freebsd && !linux && !(windows && (amd64 || 386)) + +package rawpacket + +import ( + "fmt" + "net/netip" +) + +type rawSendFD struct{} + +func openRawSender(dstIP netip.Addr) (*rawSendFD, error) { + return nil, fmt.Errorf("rawpacket: raw sockets not supported on this platform") +} + +func openRawSenderAny() (*rawSendFD, error) { + return nil, fmt.Errorf("rawpacket: raw sockets not supported on this platform") +} + +func (r *rawSendFD) send(packet []byte) error { + return fmt.Errorf("rawpacket: raw sockets not supported on this platform") +} + +func (r *rawSendFD) sendTo(packet []byte, dstIP netip.Addr) error { + return fmt.Errorf("rawpacket: raw sockets not supported on this platform") +} + +func (r *rawSendFD) close() error { + return nil +} diff --git a/transport/internet/finalmask/rawpacket/spoof_rawsend_windows.go b/transport/internet/finalmask/rawpacket/spoof_rawsend_windows.go new file mode 100644 index 000000000000..c5a29e7e0db1 --- /dev/null +++ b/transport/internet/finalmask/rawpacket/spoof_rawsend_windows.go @@ -0,0 +1,68 @@ +//go:build windows && (amd64 || 386) + +package rawpacket + +import ( + "fmt" + "net/netip" + "sync" + + "github.com/xtls/xray-core/transport/internet/finalmask/rawpacket/windivert" +) + +type rawSendFD struct { + h *windivert.Handle + // sendFn, when set, replaces the real send path (used by tests). + sendFn func(pkt []byte, dstIP netip.Addr) error + mu sync.Mutex + closed bool +} + +func openRawSender(dstIP netip.Addr) (*rawSendFD, error) { + return openRawSenderAny() +} + +// openRawSenderAny opens a WinDivert send handle. WinDivert injects +// packets from the header contents, so no destination binding is needed. +func openRawSenderAny() (*rawSendFD, error) { + h, err := windivert.Open(windivert.AcceptAll(), windivert.LayerNetwork, windivert.PriorityLowest, windivert.FlagSendOnly) + if err != nil { + return nil, fmt.Errorf("rawpacket: WinDivert open: %w", err) + } + return &rawSendFD{h: h}, nil +} + +func (r *rawSendFD) send(packet []byte) error { + return r.sendTo(packet, netip.Addr{}) +} + +// sendTo sends packet via WinDivert; the destination is read from the +// packet itself. +func (r *rawSendFD) sendTo(packet []byte, dstIP netip.Addr) error { + if r.sendFn != nil { + return r.sendFn(packet, dstIP) + } + r.mu.Lock() + defer r.mu.Unlock() + if r.closed { + return fmt.Errorf("rawpacket: WinDivert sender closed") + } + var addr windivert.Address + addr.SetIPChecksum(true) + addr.SetTCPChecksum(true) + _, err := r.h.Send(packet, &addr) + if err != nil { + return fmt.Errorf("rawpacket: WinDivert send: %w", err) + } + return nil +} + +func (r *rawSendFD) close() error { + r.mu.Lock() + defer r.mu.Unlock() + if r.closed { + return nil + } + r.closed = true + return r.h.Close() +} diff --git a/transport/internet/finalmask/rawpacket/spoof_receiver.go b/transport/internet/finalmask/rawpacket/spoof_receiver.go new file mode 100644 index 000000000000..af3814b03092 --- /dev/null +++ b/transport/internet/finalmask/rawpacket/spoof_receiver.go @@ -0,0 +1,178 @@ +package rawpacket + +import ( + "errors" + "net/netip" +) + +var errReceiverClosed = errors.New("rawpacket: receiver closed") + +// rawPktRecv is the platform-specific raw socket: unix SOCK_RAW on +// darwin/freebsd/linux, WinDivert on windows (amd64/386). +type rawPktRecv interface { + // recv returns a copy of one raw IP packet. ok is false when the + // socket is closed or a transient read failure occurred (callers + // must tolerate spurious false returns and re-try). + recv() (pkt []byte, ok bool) + // closed reports whether the socket has been closed (recv will no + // longer produce packets and errReceiverClosed is the permanent + // outcome). + closed() bool + close() +} + +type tcpReceiver struct { + raw rawPktRecv + cfg *SpoofReceiverConfig +} + +func newTCPReceiver(cfg *SpoofReceiverConfig) (*tcpReceiver, error) { + raw, err := newRawRecvSocket(ProtocolTCP, cfg.BufferSize) + if err != nil { + return nil, err + } + return &tcpReceiver{raw: raw, cfg: cfg}, nil +} + +func (r *tcpReceiver) Receive() ([]byte, netip.Addr, uint16, *TCPMeta, error) { + for { + pkt, ok := r.raw.recv() + if !ok { + if r.raw.closed() { + return nil, netip.Addr{}, 0, nil, errReceiverClosed + } + continue + } + seq, flags, payload, srcIP, dstIP, srcPort, dstPort, ok := ParseRawTCPPacket(pkt) + if !ok || dstPort != r.cfg.ListenPort { + continue + } + if r.cfg.PeerSpoofIP.IsValid() && srcIP != r.cfg.PeerSpoofIP { + continue + } + return payload, srcIP, srcPort, &TCPMeta{Seq: seq, Flags: flags, DstIP: dstIP, DstPort: dstPort}, nil + } +} + +func (r *tcpReceiver) Close() error { + r.raw.close() + return nil +} + +type udpReceiver struct { + raw rawPktRecv + cfg *SpoofReceiverConfig +} + +func newUDPReceiver(cfg *SpoofReceiverConfig) (*udpReceiver, error) { + raw, err := newRawRecvSocket(ProtocolUDP, cfg.BufferSize) + if err != nil { + return nil, err + } + return &udpReceiver{raw: raw, cfg: cfg}, nil +} + +func (r *udpReceiver) Receive() ([]byte, netip.Addr, uint16, *TCPMeta, error) { + for { + pkt, ok := r.raw.recv() + if !ok { + if r.raw.closed() { + return nil, netip.Addr{}, 0, nil, errReceiverClosed + } + continue + } + payload, srcPort, dstPort, ok := ParseUDPPacket(pkt) + if !ok || dstPort != r.cfg.ListenPort { + continue + } + srcIP, dstIP, _ := ParseSrcIP(pkt, false) + if r.cfg.PeerSpoofIP.IsValid() && srcIP != r.cfg.PeerSpoofIP { + continue + } + return payload, srcIP, srcPort, &TCPMeta{DstIP: dstIP, DstPort: dstPort}, nil + } +} + +func (r *udpReceiver) Close() error { + r.raw.close() + return nil +} + +type icmpReceiver struct { + raw rawPktRecv + cfg *SpoofReceiverConfig +} + +func newICMPReceiver(cfg *SpoofReceiverConfig) (*icmpReceiver, error) { + raw, err := newRawRecvSocket(ProtocolICMP, cfg.BufferSize) + if err != nil { + return nil, err + } + return &icmpReceiver{raw: raw, cfg: cfg}, nil +} + +func (r *icmpReceiver) Receive() ([]byte, netip.Addr, uint16, *TCPMeta, error) { + for { + pkt, ok := r.raw.recv() + if !ok { + if r.raw.closed() { + return nil, netip.Addr{}, 0, nil, errReceiverClosed + } + continue + } + id, _, payload, ok := ParseICMPv4Echo(pkt) + if !ok { + continue + } + srcIP, _, _ := ParseSrcIP(pkt, false) + if r.cfg.PeerSpoofIP.IsValid() && srcIP != r.cfg.PeerSpoofIP { + continue + } + return payload, srcIP, id, nil, nil + } +} + +func (r *icmpReceiver) Close() error { + r.raw.close() + return nil +} + +type icmpv6Receiver struct { + raw rawPktRecv + cfg *SpoofReceiverConfig +} + +func newICMPv6Receiver(cfg *SpoofReceiverConfig) (*icmpv6Receiver, error) { + // Non-standard: protocol 58 on IPv4 (same as reference) + raw, err := newRawRecvSocket(ProtocolICMPv6, cfg.BufferSize) + if err != nil { + return nil, err + } + return &icmpv6Receiver{raw: raw, cfg: cfg}, nil +} + +func (r *icmpv6Receiver) Receive() ([]byte, netip.Addr, uint16, *TCPMeta, error) { + for { + pkt, ok := r.raw.recv() + if !ok { + if r.raw.closed() { + return nil, netip.Addr{}, 0, nil, errReceiverClosed + } + continue + } + id, _, payload, ok := ParseICMPv6Echo(pkt) + if !ok { + continue + } + srcIP, _, _ := ParseSrcIP(pkt, false) + if r.cfg.PeerSpoofIP.IsValid() && srcIP != r.cfg.PeerSpoofIP { + continue + } + return payload, srcIP, id, nil, nil + } +} + +func (r *icmpv6Receiver) Close() error { + r.raw.close() + return nil +} diff --git a/transport/internet/finalmask/rawpacket/spoof_recv_stub.go b/transport/internet/finalmask/rawpacket/spoof_recv_stub.go new file mode 100644 index 000000000000..419237d0fab2 --- /dev/null +++ b/transport/internet/finalmask/rawpacket/spoof_recv_stub.go @@ -0,0 +1,21 @@ +//go:build !darwin && !freebsd && !linux && !(windows && (amd64 || 386)) + +package rawpacket + +import "fmt" + +type rawRecvSocket struct{} + +func newRawRecvSocket(proto uint8, bufSize int) (*rawRecvSocket, error) { + return nil, fmt.Errorf("rawpacket: raw sockets not supported on this platform") +} + +func (r *rawRecvSocket) recv() ([]byte, bool) { + return nil, false +} + +func (r *rawRecvSocket) closed() bool { + return true +} + +func (r *rawRecvSocket) close() {} diff --git a/transport/internet/finalmask/rawpacket/spoof_recv_unix.go b/transport/internet/finalmask/rawpacket/spoof_recv_unix.go new file mode 100644 index 000000000000..1dda4aead7f3 --- /dev/null +++ b/transport/internet/finalmask/rawpacket/spoof_recv_unix.go @@ -0,0 +1,63 @@ +//go:build darwin || freebsd || linux + +package rawpacket + +import ( + "fmt" + "runtime" + + "golang.org/x/sys/unix" +) + +type rawRecvSocket struct { + fd int + buf []byte + closedFlag bool + proto uint8 +} + +func newRawRecvSocket(proto uint8, bufSize int) (*rawRecvSocket, error) { + fd, err := unix.Socket(unix.AF_INET, unix.SOCK_RAW, int(proto)) + if err != nil { + return nil, fmt.Errorf("rawpacket: socket: %w", err) + } + if bufSize > 0 { + _ = unix.SetsockoptInt(fd, unix.SOL_SOCKET, unix.SO_RCVBUF, bufSize) + } + // 1-second timeout for clean shutdown + tv := unix.Timeval{Sec: 1, Usec: 0} + _ = unix.SetsockoptTimeval(fd, unix.SOL_SOCKET, unix.SO_RCVTIMEO, &tv) + // Linux only: attach a classic-BPF filter so the kernel drops + // non-matching protocol traffic before userspace sees it. + if runtime.GOOS == "linux" { + attachBPFFilter(fd, proto) + } + return &rawRecvSocket{fd: fd, buf: make([]byte, 65536), proto: proto}, nil +} + +func (r *rawRecvSocket) recv() ([]byte, bool) { + if r.closedFlag { + return nil, false + } + n, _, err := unix.Recvfrom(r.fd, r.buf, 0) + if err != nil { + return nil, false + } + if n == 0 { + return nil, false + } + out := make([]byte, n) + copy(out, r.buf[:n]) + return out, true +} + +func (r *rawRecvSocket) closed() bool { + return r.closedFlag +} + +func (r *rawRecvSocket) close() { + if !r.closedFlag { + r.closedFlag = true + unix.Close(r.fd) + } +} diff --git a/transport/internet/finalmask/rawpacket/spoof_recv_windows.go b/transport/internet/finalmask/rawpacket/spoof_recv_windows.go new file mode 100644 index 000000000000..a5fec04068ae --- /dev/null +++ b/transport/internet/finalmask/rawpacket/spoof_recv_windows.go @@ -0,0 +1,59 @@ +//go:build windows && (amd64 || 386) + +package rawpacket + +import ( + "fmt" + "sync" + + "github.com/xtls/xray-core/transport/internet/finalmask/rawpacket/windivert" +) + +type rawRecvSocket struct { + h *windivert.Handle + buf []byte + mu sync.Mutex + closedFlag bool + proto uint8 +} + +func newRawRecvSocket(proto uint8, bufSize int) (*rawRecvSocket, error) { + h, err := windivert.Open(windivert.AcceptAll(), windivert.LayerNetwork, windivert.PriorityLowest, windivert.FlagSniff) + if err != nil { + return nil, fmt.Errorf("rawpacket: WinDivert open: %w", err) + } + return &rawRecvSocket{h: h, buf: make([]byte, windivert.MTUMax), proto: proto}, nil +} + +func (r *rawRecvSocket) recv() ([]byte, bool) { + r.mu.Lock() + defer r.mu.Unlock() + if r.closedFlag { + return nil, false + } + n, _, err := r.h.Recv(r.buf) + if err != nil { + return nil, false + } + if n == 0 { + return nil, false + } + out := make([]byte, n) + copy(out, r.buf[:n]) + return out, true +} + +func (r *rawRecvSocket) closed() bool { + r.mu.Lock() + defer r.mu.Unlock() + return r.closedFlag +} + +func (r *rawRecvSocket) close() { + r.mu.Lock() + defer r.mu.Unlock() + if !r.closedFlag { + r.closedFlag = true + _ = r.h.Close() + } +} diff --git a/transport/internet/finalmask/rawpacket/spoof_relay.go b/transport/internet/finalmask/rawpacket/spoof_relay.go new file mode 100644 index 000000000000..760cfe67bd3c --- /dev/null +++ b/transport/internet/finalmask/rawpacket/spoof_relay.go @@ -0,0 +1,353 @@ +package rawpacket + +import ( + "errors" + "net" + "net/netip" + "sync" + "time" +) + +type Relay struct { + cfg *RelayConfig + psk []byte + recver SpoofReceiver + sender SpoofSender + done chan struct{} + closeOnce sync.Once + icmpSuppressed bool + maxPayload int + sessionTimeout time.Duration + rstManaged bool + masq *masquerade + + man *SessionManager + + recentSIDs map[[8]byte]time.Time + recentMu sync.Mutex +} + +const ( + relaySessionTimeout = 120 * time.Second + relaySIDRemember = 10 * time.Minute +) + +func NewRelay(cfg *RelayConfig) (*Relay, error) { + if cfg.SendTransport == "" { + cfg.SendTransport = "udp" + } + if cfg.RecvTransport == "" { + cfg.RecvTransport = "tcp" + } + if len(cfg.Auth) == 0 { + return nil, errors.New("rawpacket: auth (PSK) required in remote mode") + } + + if cfg.RecvTransport == "icmp" || cfg.RecvTransport == "icmpv6" { + if suppressICMPEchoReply() { + cfg.icmpSuppressed = true + } + } + + var spoofIPs []netip.Addr + if len(cfg.SpoofIPs) > 0 { + spoofIPs, _ = ParseIPs(cfg.SpoofIPs) + } + if len(spoofIPs) == 0 && cfg.SpoofIP.IsValid() { + spoofIPs = []netip.Addr{cfg.SpoofIP} + } + if len(spoofIPs) == 0 { + spoofIPs = []netip.Addr{netip.MustParseAddr("127.0.0.1")} + } + + recver, err := NewReceiver(cfg.RecvTransport, &SpoofReceiverConfig{ + ListenPort: cfg.ListenPort, + PeerSpoofIP: cfg.PeerSpoofIP, + BufferSize: 4 * 1024 * 1024, + }) + if err != nil { + if cfg.icmpSuppressed { + restoreICMPEchoReply() + } + return nil, err + } + + sender, err := NewSender(cfg.SendTransport, &SpoofSenderConfig{ + SourceIPs: spoofIPs, + SourcePort: cfg.SpoofPort, + TTL: 64, + Server: true, + }) + if err != nil { + recver.Close() + if cfg.icmpSuppressed { + restoreICMPEchoReply() + } + return nil, err + } + + r := &Relay{ + cfg: cfg, + psk: []byte(cfg.Auth), + recver: recver, + sender: sender, + done: make(chan struct{}), + icmpSuppressed: cfg.icmpSuppressed, + maxPayload: maxPayloadForMTU(cfg.Mtu), + sessionTimeout: relaySessionTimeout, + man: NewSessionManager(), + recentSIDs: make(map[[8]byte]time.Time), + } + if cfg.SuppressRst { + r.rstManaged = suppressKernelRST(cfg.ListenPort) + } + masq, masqErr := newMasquerade(cfg.Masquerade, cfg.ListenPort) + if masqErr != nil { + r.Close() + return nil, masqErr + } + r.masq = masq + return r, nil +} + +func (r *Relay) Run() { + go r.uplinkLoop() + go r.janitorLoop() + <-r.done +} + +func (r *Relay) dialTarget() (net.Conn, error) { + return net.DialTimeout(r.cfg.ForwardTransport, r.cfg.ForwardAddr, 10*time.Second) +} + +func (r *Relay) uplinkLoop() { + for { + select { + case <-r.done: + return + default: + } + + pkt, srcIP, srcPort, tcp, err := r.recver.Receive() + if err != nil { + return + } + if len(pkt) == 0 { + // A TCP segment without payload is never a tunnel frame: + // bare SYNs are handshake probes from scanners. + if r.masq != nil && tcp != nil && tcp.Flags&TCPFlagSyn != 0 && tcp.Flags&TCPFlagAck == 0 { + r.masq.onTCPSYN(tcp.DstIP, tcp.DstPort, srcIP, srcPort, tcp.Seq) + } + continue + } + r.handleFrame(pkt, srcIP, srcPort, tcp) + } +} + +func (r *Relay) handleFrame(pkt []byte, srcIP netip.Addr, srcPort uint16, tcp *TCPMeta) { + sid, ok := frameSessionID(pkt) + if !ok { + r.masqueradeProbe(pkt, srcIP, srcPort, tcp) + return + } + s := r.man.Get(sid) + if s == nil { + if !r.handleNewSession(sid, pkt, srcIP, srcPort) { + r.masqueradeProbe(pkt, srcIP, srcPort, tcp) + } + return + } + if !r.deliverToSession(s, pkt, tcp) { + r.masqueradeProbe(pkt, srcIP, srcPort, tcp) + } +} + +// masqueradeProbe answers packets that do not belong to any tunnel +// session (failed frame parse or decryption) with fake service traffic. +func (r *Relay) masqueradeProbe(pkt []byte, srcIP netip.Addr, srcPort uint16, tcp *TCPMeta) { + if r.masq == nil || tcp == nil { + return + } + if tcp.Flags != 0 { + r.masq.onTCPData(tcp.DstIP, tcp.DstPort, srcIP, srcPort, tcp.Seq, pkt) + } else { + r.masq.onUDP(tcp.DstIP, tcp.DstPort, srcIP, srcPort, pkt) + } +} + +func (r *Relay) handleNewSession(sid [8]byte, pkt []byte, srcIP netip.Addr, srcPort uint16) bool { + if r.recentSIDSeen(sid) { + // Replay of a session that was already torn down: drop. + return false + } + crypto, err := newFrameCrypto(r.psk, sid) + if err != nil { + return false + } + payload, flags, err := crypto.open(pkt, false) + if err != nil { + return false + } + if flags&frameFlagKeepalive != 0 { + // A keepalive for a session that no longer exists: ignore. + return false + } + targetConn, err := r.dialTarget() + if err != nil { + return false + } + s := r.man.Add(sid, srcIP, srcPort, targetConn, crypto, newTCPSimState()) + r.rememberSID(sid) + go r.forwardSession(s) + if len(payload) > 0 { + writeTarget(s, payload) + } + return true +} + +func (r *Relay) deliverToSession(s *RelaySession, pkt []byte, tcp *TCPMeta) bool { + s.mu.Lock() + if s.closed { + s.mu.Unlock() + return false + } + s.mu.Unlock() + + payload, _, err := s.crypto.open(pkt, false) + if err != nil { + return false + } + if tcp != nil && tcp.Flags != 0 { + s.tcp.observeClientSeq(tcp.Seq, len(pkt)) + } + s.mu.Lock() + s.LastSeen = time.Now() + s.mu.Unlock() + + if len(payload) > 0 { + if !writeTarget(s, payload) { + r.man.Remove(s.ID) + return false + } + } + return true +} + +// writeTarget writes the whole payload to the target connection, handling +// partial writes. Returns false if the write failed (caller should remove +// the session). +func writeTarget(s *RelaySession, data []byte) bool { + if s.TargetConn == nil { + return false + } + _ = s.TargetConn.SetWriteDeadline(time.Now().Add(30 * time.Second)) + n := 0 + for n < len(data) { + m, err := s.TargetConn.Write(data[n:]) + if err != nil { + return false + } + if m == 0 { + return false + } + n += m + } + return true +} + +// forwardSession pumps target->client data for one session. It exits on +// read error or EOF and removes the session. +func (r *Relay) forwardSession(s *RelaySession) { + buf := make([]byte, 64*1024) + for { + n, err := s.TargetConn.Read(buf) + if err != nil { + r.man.Remove(s.ID) + return + } + if n == 0 { + continue + } + frames, ferr := s.crypto.sealSplit(true, buf[:n], r.maxPayload, false) + if ferr != nil { + continue + } + ok := true + for _, f := range frames { + if serr := r.sender.Send(f, s.ClientIP, s.ClientPort, s.tcp); serr != nil { + ok = false + break + } + } + if ok { + s.mu.Lock() + s.LastSeen = time.Now() + s.mu.Unlock() + } else { + r.man.Remove(s.ID) + return + } + } +} + +// janitorLoop reaps sessions idle for longer than sessionTimeout and +// prunes the recent-session-ID anti-replay set. +func (r *Relay) janitorLoop() { + t := time.NewTicker(15 * time.Second) + defer t.Stop() + for { + select { + case <-r.done: + return + case <-t.C: + now := time.Now() + for _, s := range r.man.All() { + s.mu.Lock() + idle := now.Sub(s.LastSeen) + s.mu.Unlock() + if idle > r.sessionTimeout { + r.man.Remove(s.ID) + } + } + r.pruneRecentSIDs(now) + } + } +} + +func (r *Relay) rememberSID(sid [8]byte) { + r.recentMu.Lock() + r.recentSIDs[sid] = time.Now() + r.recentMu.Unlock() +} + +func (r *Relay) recentSIDSeen(sid [8]byte) bool { + r.recentMu.Lock() + defer r.recentMu.Unlock() + _, ok := r.recentSIDs[sid] + return ok +} + +func (r *Relay) pruneRecentSIDs(now time.Time) { + r.recentMu.Lock() + defer r.recentMu.Unlock() + for sid, t := range r.recentSIDs { + if now.Sub(t) > relaySIDRemember { + delete(r.recentSIDs, sid) + } + } +} + +func (r *Relay) Close() { + r.closeOnce.Do(func() { + close(r.done) + r.recver.Close() + r.sender.Close() + r.man.Close() + if r.icmpSuppressed { + restoreICMPEchoReply() + } + if r.rstManaged { + restoreKernelRST(r.cfg.ListenPort, true) + } + }) +} diff --git a/transport/internet/finalmask/rawpacket/spoof_rst_linux.go b/transport/internet/finalmask/rawpacket/spoof_rst_linux.go new file mode 100644 index 000000000000..a87d2bb82296 --- /dev/null +++ b/transport/internet/finalmask/rawpacket/spoof_rst_linux.go @@ -0,0 +1,42 @@ +package rawpacket + +import ( + "log" + "os/exec" + "strconv" +) + +// suppressKernelRST installs an iptables rule that drops the kernel's +// RST replies for the relay listen port (the fake TCP handshake has no +// kernel socket behind it, so the kernel would answer our own SYN with +// RST). Only RSTs matching the relay port are dropped; the raw socket's +// spoofed packets are unaffected. Returns true when the rule was +// installed. +func suppressKernelRST(port uint16) bool { + if port == 0 { + return false + } + rule := []string{"-I", "OUTPUT", "-p", "tcp", "--tcp-flags", "RST", "RST", "--sport", strconv.Itoa(int(port)), "-j", "DROP"} + err := exec.Command("iptables", rule...).Run() + if err != nil { + log.Printf("[rawpacket] failed to suppress kernel RST on port %d: %v", port, err) + return false + } + log.Printf("[rawpacket] suppressed kernel RST on port %d", port) + return true +} + +// restoreKernelRST removes the rule installed by suppressKernelRST. +// managed must be the value returned by suppressKernelRST. +func restoreKernelRST(port uint16, managed bool) { + if !managed || port == 0 { + return + } + rule := []string{"-D", "OUTPUT", "-p", "tcp", "--tcp-flags", "RST", "RST", "--sport", strconv.Itoa(int(port)), "-j", "DROP"} + err := exec.Command("iptables", rule...).Run() + if err != nil { + log.Printf("[rawpacket] failed to restore kernel RST on port %d: %v", port, err) + return + } + log.Printf("[rawpacket] restored kernel RST on port %d", port) +} diff --git a/transport/internet/finalmask/rawpacket/spoof_rst_stub.go b/transport/internet/finalmask/rawpacket/spoof_rst_stub.go new file mode 100644 index 000000000000..337542156a84 --- /dev/null +++ b/transport/internet/finalmask/rawpacket/spoof_rst_stub.go @@ -0,0 +1,17 @@ +//go:build !linux + +package rawpacket + +import "log" + +// suppressKernelRST is a no-op off Linux: the kernel only emits RST +// replies on the host that owns the port, and raw sockets are privileged +// there anyway. Return false so the caller knows no rule is managed. +func suppressKernelRST(port uint16) bool { + if port != 0 { + log.Printf("[rawpacket] kernel RST suppression only supported on linux (port %d left as-is)", port) + } + return false +} + +func restoreKernelRST(port uint16, managed bool) {} diff --git a/transport/internet/finalmask/rawpacket/spoof_sender.go b/transport/internet/finalmask/rawpacket/spoof_sender.go new file mode 100644 index 000000000000..ea4066e35905 --- /dev/null +++ b/transport/internet/finalmask/rawpacket/spoof_sender.go @@ -0,0 +1,217 @@ +package rawpacket + +import ( + "math/rand" + "net/netip" + "sync" +) + +type tcpSender struct { + srcIP netip.Addr + srcPort uint16 + ttl uint8 + ipID uint16 + server bool + fd *rawSendFD + mu sync.Mutex +} + +func newTCPSender(cfg *SpoofSenderConfig) (*tcpSender, error) { + ips := cfg.SourceIPs + if len(ips) == 0 { + ips = []netip.Addr{cfg.SourceIP} + } + fd, err := openRawSender(ips[0]) + if err != nil { + return nil, err + } + return &tcpSender{ + srcIP: ips[0], + srcPort: cfg.SourcePort, + ttl: cfg.TTL, + ipID: uint16(rand.Intn(65535)), + server: cfg.Server, + fd: fd, + }, nil +} + +func (s *tcpSender) nextIPID() uint16 { + s.mu.Lock() + defer s.mu.Unlock() + s.ipID++ + return s.ipID +} + +func (s *tcpSender) Send(payload []byte, dstIP netip.Addr, dstPort uint16, tcp *TCPSimState) error { + if tcp == nil { + return nil + } + seq := tcp.nextSeq(len(payload)) + var flags uint8 + if s.server { + flags = tcp.serverFlags() + } else { + flags = tcp.clientFlags() + } + pkt := BuildTCPPacket(s.srcIP, dstIP, s.srcPort, dstPort, seq, tcp.ack(), flags, payload, s.ttl, s.nextIPID(), flags&TCPFlagSyn != 0) + return s.fd.send(pkt) +} + +func (s *tcpSender) Close() error { + if s.fd != nil { + s.fd.close() + } + return nil +} + +type udpSender struct { + srcIP netip.Addr + srcPort uint16 + ttl uint8 + ipID uint16 + fd *rawSendFD + mu sync.Mutex +} + +func newUDPSender(cfg *SpoofSenderConfig) (*udpSender, error) { + ips := cfg.SourceIPs + if len(ips) == 0 { + ips = []netip.Addr{cfg.SourceIP} + } + fd, err := openRawSender(ips[0]) + if err != nil { + return nil, err + } + return &udpSender{ + srcIP: ips[0], + srcPort: cfg.SourcePort, + ttl: cfg.TTL, + ipID: uint16(rand.Intn(65535)), + fd: fd, + }, nil +} + +func (s *udpSender) nextIPID() uint16 { + s.mu.Lock() + defer s.mu.Unlock() + s.ipID++ + return s.ipID +} + +func (s *udpSender) Send(payload []byte, dstIP netip.Addr, dstPort uint16, tcp *TCPSimState) error { + pkt := BuildRawUDP(s.srcIP, dstIP, s.srcPort, dstPort, payload, s.ttl, s.nextIPID()) + return s.fd.send(pkt) +} + +func (s *udpSender) Close() error { + if s.fd != nil { + s.fd.close() + } + return nil +} + +type icmpSender struct { + srcIP netip.Addr + id uint16 + seq uint16 + ttl uint8 + ipID uint16 + seqMu sync.Mutex + fd *rawSendFD +} + +func newICMPSender(cfg *SpoofSenderConfig) (*icmpSender, error) { + ips := cfg.SourceIPs + if len(ips) == 0 { + ips = []netip.Addr{cfg.SourceIP} + } + fd, err := openRawSender(ips[0]) + if err != nil { + return nil, err + } + return &icmpSender{ + srcIP: ips[0], + id: cfg.SourcePort, + seq: 1, + ttl: cfg.TTL, + ipID: uint16(rand.Intn(65535)), + fd: fd, + }, nil +} + +func (s *icmpSender) nextIPID() uint16 { + s.seqMu.Lock() + defer s.seqMu.Unlock() + s.ipID++ + return s.ipID +} + +func (s *icmpSender) Send(payload []byte, dstIP netip.Addr, dstPort uint16, tcp *TCPSimState) error { + s.seqMu.Lock() + seq := s.seq + s.seq++ + s.seqMu.Unlock() + + pkt := BuildICMPv4Echo(s.srcIP, dstIP, s.id, seq, payload, s.ttl, s.nextIPID()) + return s.fd.send(pkt) +} + +func (s *icmpSender) Close() error { + if s.fd != nil { + s.fd.close() + } + return nil +} + +type icmpv6Sender struct { + srcIP netip.Addr + id uint16 + seq uint16 + ttl uint8 + ipID uint16 + seqMu sync.Mutex + fd *rawSendFD +} + +func newICMPv6Sender(cfg *SpoofSenderConfig) (*icmpv6Sender, error) { + ips := cfg.SourceIPs + if len(ips) == 0 { + ips = []netip.Addr{cfg.SourceIP} + } + fd, err := openRawSender(ips[0]) + if err != nil { + return nil, err + } + return &icmpv6Sender{ + srcIP: ips[0], + id: cfg.SourcePort, + seq: 1, + ttl: cfg.TTL, + ipID: uint16(rand.Intn(65535)), + fd: fd, + }, nil +} + +func (s *icmpv6Sender) nextIPID() uint16 { + s.seqMu.Lock() + defer s.seqMu.Unlock() + s.ipID++ + return s.ipID +} + +func (s *icmpv6Sender) Send(payload []byte, dstIP netip.Addr, dstPort uint16, tcp *TCPSimState) error { + s.seqMu.Lock() + seq := s.seq + s.seq++ + s.seqMu.Unlock() + + pkt := BuildICMPv6Echo(s.srcIP, dstIP, s.id, seq, payload, s.ttl, s.nextIPID()) + return s.fd.send(pkt) +} + +func (s *icmpv6Sender) Close() error { + if s.fd != nil { + s.fd.close() + } + return nil +} diff --git a/transport/internet/finalmask/rawpacket/spoof_session.go b/transport/internet/finalmask/rawpacket/spoof_session.go new file mode 100644 index 000000000000..cbfdef817006 --- /dev/null +++ b/transport/internet/finalmask/rawpacket/spoof_session.go @@ -0,0 +1,85 @@ +package rawpacket + +import ( + "net" + "net/netip" + "sync" + "time" +) + +type RelaySession struct { + ID [8]byte + ClientIP netip.Addr + ClientPort uint16 + TargetConn net.Conn + crypto *frameCrypto + tcp *TCPSimState + LastSeen time.Time + mu sync.Mutex + closed bool +} + +type SessionManager struct { + sessions map[[8]byte]*RelaySession + mu sync.Mutex +} + +func NewSessionManager() *SessionManager { + return &SessionManager{ + sessions: make(map[[8]byte]*RelaySession), + } +} + +func (sm *SessionManager) Add(id [8]byte, clientIP netip.Addr, clientPort uint16, targetConn net.Conn, crypto *frameCrypto, tcp *TCPSimState) *RelaySession { + sm.mu.Lock() + defer sm.mu.Unlock() + s := &RelaySession{ + ID: id, + ClientIP: clientIP, + ClientPort: clientPort, + TargetConn: targetConn, + crypto: crypto, + tcp: tcp, + LastSeen: time.Now(), + } + sm.sessions[id] = s + return s +} + +func (sm *SessionManager) Get(id [8]byte) *RelaySession { + sm.mu.Lock() + defer sm.mu.Unlock() + return sm.sessions[id] +} + +// Remove is idempotent: it closes the target connection, marks the +// session closed and drops it from the map. +func (sm *SessionManager) Remove(id [8]byte) { + sm.mu.Lock() + defer sm.mu.Unlock() + if s, ok := sm.sessions[id]; ok { + s.closed = true + s.TargetConn.Close() + delete(sm.sessions, id) + } +} + +func (sm *SessionManager) All() []*RelaySession { + sm.mu.Lock() + defer sm.mu.Unlock() + out := make([]*RelaySession, 0, len(sm.sessions)) + for _, s := range sm.sessions { + out = append(out, s) + } + return out +} + +func (sm *SessionManager) Close() { + sm.mu.Lock() + defer sm.mu.Unlock() + for _, s := range sm.sessions { + s.closed = true + s.TargetConn.Close() + } + clear(sm.sessions) +} diff --git a/transport/internet/finalmask/rawpacket/spoof_source_ip.go b/transport/internet/finalmask/rawpacket/spoof_source_ip.go new file mode 100644 index 000000000000..58a232a6093f --- /dev/null +++ b/transport/internet/finalmask/rawpacket/spoof_source_ip.go @@ -0,0 +1,33 @@ +package rawpacket + +import ( + "net/netip" + "sync/atomic" +) + +type SourceIPRotator struct { + ips []netip.Addr + next atomic.Uint64 +} + +func NewSourceIPRotator(ips []netip.Addr) *SourceIPRotator { + if len(ips) == 0 { + return nil + } + return &SourceIPRotator{ips: ips} +} + +func (r *SourceIPRotator) Next() netip.Addr { + if r == nil || len(r.ips) == 0 { + return netip.Addr{} + } + i := r.next.Add(1) - 1 + return r.ips[i%uint64(len(r.ips))] +} + +func (r *SourceIPRotator) Len() int { + if r == nil { + return 0 + } + return len(r.ips) +} diff --git a/transport/internet/finalmask/rawpacket/spoof_tcp.go b/transport/internet/finalmask/rawpacket/spoof_tcp.go new file mode 100644 index 000000000000..2cfe21ef0b57 --- /dev/null +++ b/transport/internet/finalmask/rawpacket/spoof_tcp.go @@ -0,0 +1,254 @@ +package rawpacket + +import ( + "encoding/binary" + "net/netip" +) + +const ( + tcpMaxSegmentMSS = 1460 + tcpWindowScale = 7 +) + +// tcpOptions builds the TCP options for an outbound segment. SYN segments +// carry MSS/SACK-permitted/TS/WScale like Linux; data segments keep the +// timestamp option (RFC 7323 requires it on every segment once +// negotiated). Header size: 20 bytes for SYN, 12 for data. +func tcpOptions(syn bool, ts uint32, tsecr uint32) []byte { + if syn { + opt := make([]byte, 0, 20) + opt = append(opt, 2, 4, byte(tcpMaxSegmentMSS>>8), byte(tcpMaxSegmentMSS&0xff)) // MSS + opt = append(opt, 4, 2) // SACK permitted + opt = append(opt, 8, 10) // TS + opt = binary.BigEndian.AppendUint32(opt, ts) + opt = binary.BigEndian.AppendUint32(opt, tsecr) + opt = append(opt, 1) // NOP + opt = append(opt, 3, 3, tcpWindowScale) + return opt + } + opt := make([]byte, 0, 12) + opt = append(opt, 1, 1, 8, 10) + opt = binary.BigEndian.AppendUint32(opt, ts) + opt = binary.BigEndian.AppendUint32(opt, tsecr) + return opt +} + +// BuildTCPPacket builds a TCP segment over IPv4 with plausible options, +// DF set, and a caller-provided (monotonic) IP ID. +func BuildTCPPacket(srcIP, dstIP netip.Addr, srcPort, dstPort uint16, seqNum, ackNum uint32, flags uint8, payload []byte, ttl uint8, ipID uint16, syn bool) []byte { + opts := tcpOptions(syn, tsVal(), 0) + tcpHdrLen := 20 + len(opts) + totalLen := 20 + tcpHdrLen + len(payload) + + frame := make([]byte, totalLen) + ip := BuildIPv4Header(uint16(totalLen), ipID, ttl, 6, srcIP, dstIP, true) + copy(frame, ip) + + tcp := frame[20:] + binary.BigEndian.PutUint16(tcp[0:], srcPort) + binary.BigEndian.PutUint16(tcp[2:], dstPort) + binary.BigEndian.PutUint32(tcp[4:], seqNum) + binary.BigEndian.PutUint32(tcp[8:], ackNum) + tcp[12] = byte((tcpHdrLen / 4) << 4) + tcp[13] = flags + binary.BigEndian.PutUint16(tcp[14:], 65535) + + copy(tcp[20:], opts) + if len(payload) > 0 { + copy(tcp[tcpHdrLen:], payload) + } + + pseudo := IPv4PseudoHeaderChecksum(srcIP, dstIP, 6, uint16(tcpHdrLen+len(payload))) + csum := Checksum(tcp[:tcpHdrLen+len(payload)], pseudo) + binary.BigEndian.PutUint16(tcp[16:], ^csum) + + return frame +} + +func BuildICMPv4Echo(srcIP, dstIP netip.Addr, id, seq uint16, payload []byte, ttl uint8, ipID uint16) []byte { + totalLen := 20 + 8 + len(payload) + frame := make([]byte, totalLen) + ip := BuildIPv4Header(uint16(totalLen), ipID, ttl, 1, srcIP, dstIP, false) + copy(frame, ip) + + icmp := frame[20:] + icmp[0] = 8 // Echo Request + icmp[1] = 0 + binary.BigEndian.PutUint16(icmp[4:], id) + binary.BigEndian.PutUint16(icmp[6:], seq) + copy(icmp[8:], payload) + + // ICMP checksum covers ICMP header + payload + csum := Checksum(icmp[:8+len(payload)], 0) + binary.BigEndian.PutUint16(icmp[2:], ^csum) + return frame +} + +func BuildICMPv6Echo(srcIP, dstIP netip.Addr, id, seq uint16, payload []byte, ttl uint8, ipID uint16) []byte { + // Non-standard: ICMPv6 Echo Request (type 128) over IPv4 header with protocol 58. + icmpLen := 8 + len(payload) + totalLen := 20 + icmpLen + frame := make([]byte, totalLen) + ip := BuildIPv4Header(uint16(totalLen), ipID, ttl, 58, srcIP, dstIP, false) + copy(frame, ip) + + icmp := frame[20:] + icmp[0] = 128 // Echo Request + icmp[1] = 0 + binary.BigEndian.PutUint16(icmp[4:], id) + binary.BigEndian.PutUint16(icmp[6:], seq) + copy(icmp[8:], payload) + + // ICMPv6 checksum with IPv4 pseudo-header (protocol 58) + pseudo := IPv4PseudoHeaderChecksum(srcIP, dstIP, 58, uint16(icmpLen)) + csum := Checksum(icmp[:icmpLen], pseudo) + binary.BigEndian.PutUint16(icmp[2:], ^csum) + return frame +} + +func BuildRawUDP(srcIP, dstIP netip.Addr, srcPort, dstPort uint16, payload []byte, ttl uint8, ipID uint16) []byte { + ipHdrLen := 20 + udpHdrLen := 8 + totalLen := ipHdrLen + udpHdrLen + len(payload) + + frame := make([]byte, totalLen) + ip := BuildIPv4Header(uint16(totalLen), ipID, ttl, 17, srcIP, dstIP, false) + copy(frame, ip) + + udp := frame[ipHdrLen:] + binary.BigEndian.PutUint16(udp[0:], srcPort) + binary.BigEndian.PutUint16(udp[2:], dstPort) + udpLen := uint16(udpHdrLen + len(payload)) + binary.BigEndian.PutUint16(udp[4:], udpLen) + binary.BigEndian.PutUint16(udp[6:], 0) // checksum = 0 (optional in IPv4) + + if len(payload) > 0 { + copy(frame[ipHdrLen+udpHdrLen:], payload) + } + + return frame +} + +func ParseSrcIP(buf []byte, isV6 bool) (netip.Addr, netip.Addr, bool) { + if len(buf) < 20 { + return netip.Addr{}, netip.Addr{}, false + } + if buf[0]>>4 != 4 { + return netip.Addr{}, netip.Addr{}, false + } + src, _ := netip.AddrFromSlice(buf[12:16]) + dst, _ := netip.AddrFromSlice(buf[16:20]) + return src, dst, true +} + +func ParseRawTCPPacket(buf []byte) (seq uint32, flags uint8, payload []byte, srcIP netip.Addr, dstIP netip.Addr, srcPort, dstPort uint16, ok bool) { + if len(buf) < 40 { + return + } + if buf[0]>>4 != 4 { + return + } + ihl := (buf[0] & 0x0f) * 4 + if int(ihl) < 20 || int(ihl)+20 > len(buf) { + return + } + if buf[9] != 6 { + return + } + srcIP, _ = netip.AddrFromSlice(buf[12:16]) + dstIP, _ = netip.AddrFromSlice(buf[16:20]) + tcp := buf[ihl:] + seq = binary.BigEndian.Uint32(tcp[4:]) + flags = tcp[13] + srcPort = binary.BigEndian.Uint16(tcp[0:]) + dstPort = binary.BigEndian.Uint16(tcp[2:]) + do := int((tcp[12] >> 4) * 4) + ihlInt := int(ihl) + if do < 20 || ihlInt+do > len(buf) { + return + } + payload = buf[ihlInt+do:] + ok = true + return +} + +func ParseUDPPacket(buf []byte) (payload []byte, srcPort, dstPort uint16, ok bool) { + if len(buf) < 28 { + return + } + ihl := (buf[0] & 0x0f) * 4 + if int(ihl) < 20 { + return + } + if buf[9] != 17 { + return + } + udp := buf[ihl:] + srcPort = binary.BigEndian.Uint16(udp[0:]) + dstPort = binary.BigEndian.Uint16(udp[2:]) + udpLen := int(binary.BigEndian.Uint16(udp[4:])) + if udpLen < 8 || int(ihl)+udpLen > len(buf) { + return + } + payload = udp[8:udpLen] + ok = true + return +} + +func ParseICMPv4Echo(buf []byte) (id, seq uint16, payload []byte, ok bool) { + if len(buf) < 28 { + return + } + ihl := (buf[0] & 0x0f) * 4 + if int(ihl) < 20 { + return + } + if buf[9] != 1 { + return + } + icmp := buf[ihl:] + if len(icmp) < 8 { + return + } + if icmp[0] != 8 { + return + } + id = binary.BigEndian.Uint16(icmp[4:]) + seq = binary.BigEndian.Uint16(icmp[6:]) + payload = icmp[8:] + ok = true + return +} + +func ParseICMPv6Echo(buf []byte) (id, seq uint16, payload []byte, ok bool) { + if len(buf) < 28 { + return + } + var hdrLen int + switch buf[0] >> 4 { + case 4: + if buf[9] != 58 { + return + } + hdrLen = int(buf[0]&0x0f) * 4 + case 6: + if buf[6] != 58 { + return + } + hdrLen = 40 + default: + return + } + if hdrLen < 20 || len(buf) < hdrLen+8 { + return + } + icmp := buf[hdrLen:] + if icmp[0] != 128 { + return + } + id = binary.BigEndian.Uint16(icmp[4:]) + seq = binary.BigEndian.Uint16(icmp[6:]) + payload = icmp[8:] + ok = true + return +} diff --git a/transport/internet/finalmask/rawpacket/spoof_tcp_test.go b/transport/internet/finalmask/rawpacket/spoof_tcp_test.go new file mode 100644 index 000000000000..613426462b93 --- /dev/null +++ b/transport/internet/finalmask/rawpacket/spoof_tcp_test.go @@ -0,0 +1,159 @@ +package rawpacket + +import ( + "net/netip" + "testing" +) + +func TestTCPSimStateClient(t *testing.T) { + st := newTCPSimState() + if st.clientFlags() != TCPFlagSyn { + t.Fatalf("first client segment should be SYN, got %#x", st.clientFlags()) + } + seq := st.nextSeq(100) + if seq != st.isn { + t.Fatalf("first data seq should be ISN, got %d want %d", seq, st.isn) + } + if st.clientFlags() != TCPFlagAck { + t.Fatalf("second client segment should be ACK, got %#x", st.clientFlags()) + } + if got := st.ack(); got != 0 { + t.Fatalf("ack before observing peer should be 0, got %d", got) + } + // peer handshake: SYN consumes one byte, then 500 bytes of data + st.observePeer(1000, 0) + if st.ack() != 1001 { + t.Fatalf("ack after peer SYN should be seq+1, got %d want 1001", st.ack()) + } + st.observePeer(1001, 500) + if st.ack() != 1501 { + t.Fatalf("ack should be peer seq+len+1, got %d want 1501", st.ack()) + } + // zero-length segments (keepalives) must not advance the sequence + if st.nextSeq(0) != st.isn+100 { + t.Fatalf("zero-length segment advanced seq: got %d want %d", st.nextSeq(0), st.isn+100) + } + // nextSeq returns the segment's own seq (pre-advance) + if got := st.nextSeq(10); got != st.isn+100 { + t.Fatalf("data after keepalive should be isn+100, got %d", got) + } + if got := st.nextSeq(1); got != st.isn+110 { + t.Fatalf("next segment should be isn+110, got %d", got) + } +} + +func TestTCPSimStateServer(t *testing.T) { + st := newTCPSimState() + if st.serverFlags() != TCPFlagSyn|TCPFlagAck { + t.Fatalf("first server segment should be SYN|ACK, got %#x", st.serverFlags()) + } + if st.serverFlags() != TCPFlagAck { + t.Fatalf("second server segment should be ACK, got %#x", st.serverFlags()) + } + st.observeClientSeq(777, 0) + if st.ack() != 778 { + t.Fatalf("server ack should be observed client seq+1, got %d want 778", st.ack()) + } + st.observeClientSeq(778, 20) + if st.ack() != 798 { + t.Fatalf("server ack should advance by payload length, got %d want 798", st.ack()) + } + seq := st.nextSeq(50) + if seq != st.isn { + t.Fatalf("server data should start at its ISN, got %d", seq) + } + if got := st.nextSeq(30); got != st.isn+50 { + t.Fatalf("server second segment should be isn+50, got %d", got) + } +} + +func TestBuildTCPPacketOptionsAndFlags(t *testing.T) { + src := netip.MustParseAddr("1.2.3.4") + dst := netip.MustParseAddr("5.6.7.8") + st := newTCPSimState() + + // SYN segment: 20 ip + 20 tcp + 20 options + syn := BuildTCPPacket(src, dst, 12345, 443, st.isn, 0, TCPFlagSyn, nil, 64, 100, true) + if len(syn) != 20+40 { + t.Fatalf("SYN should be 60 bytes (20 ip + 40 tcp w/ 20 opts), got %d", len(syn)) + } + if syn[0]>>4 != 4 { + t.Fatalf("not IPv4: %#x", syn[0]) + } + // DF bit set + if syn[6]&0x40 == 0 { + t.Fatal("DF bit not set") + } + // IP ID + if id := uint16(syn[4])<<8 | uint16(syn[5]); id != 100 { + t.Fatalf("IP ID = %d, want 100", id) + } + // data offset: 40 bytes tcp => 10 words + if syn[32]>>4 != 10 { + t.Fatalf("TCP data offset = %d, want 10", syn[32]>>4) + } + // MSS option at offset 20 + if syn[40] != 2 || syn[41] != 4 { + t.Fatal("MSS option kind not found") + } + if mss := uint16(syn[42])<<8 | uint16(syn[43]); mss != tcpMaxSegmentMSS { + t.Fatalf("MSS = %d, want %d", mss, tcpMaxSegmentMSS) + } + // checksum sanity: valid checksum means header verifies + checkTCPChecksum(t, syn) + + // data segment: ACK only, 12-byte options + payload := make([]byte, 100) + data := BuildTCPPacket(src, dst, 12345, 443, st.isn, 1000, TCPFlagAck, payload, 64, 101, false) + if len(data) != 20+32+100 { + t.Fatalf("data seg should be 152 bytes, got %d", len(data)) + } + if data[32]>>4 != 8 { + t.Fatalf("data offset = %d, want 8", data[32]>>4) + } + if data[40] != 1 || data[41] != 1 || data[42] != 8 || data[43] != 10 { + t.Fatal("data segment should carry NOP NOP TS options") + } + checkTCPChecksum(t, data) +} + +func checkTCPChecksum(t *testing.T, pkt []byte) { + t.Helper() + pseudo := IPv4PseudoHeaderChecksum( + netip.AddrFrom4([4]byte{pkt[12], pkt[13], pkt[14], pkt[15]}), + netip.AddrFrom4([4]byte{pkt[16], pkt[17], pkt[18], pkt[19]}), + pkt[9], + uint16(len(pkt)-20), + ) + if csum := Checksum(pkt[20:], pseudo); csum != 0xffff { + t.Fatalf("TCP checksum invalid: %#x", csum) + } +} + +func TestMaxPayloadForMTU(t *testing.T) { + if got := maxPayloadForMTU(0); got != frameMaxPayload { + t.Fatalf("default should be frameMaxPayload, got %d", got) + } + if got := maxPayloadForMTU(1500); got != 1500-20-40-frameOverhead { + t.Fatalf("1500 MTU: got %d", got) + } + if got := maxPayloadForMTU(100); got < 1 { + t.Fatalf("tiny MTU should clamp to >= 1, got %d", got) + } + if got := maxPayloadForMTU(1 << 20); got != frameMaxPayload { + t.Fatalf("huge MTU should cap at frameMaxPayload, got %d", got) + } +} + +func TestBuildTCPPacketIPIDMonotonic(t *testing.T) { + src := netip.MustParseAddr("1.2.3.4") + dst := netip.MustParseAddr("5.6.7.8") + prev := uint16(65000) + for i := 0; i < 100; i++ { + prev++ + pkt := BuildTCPPacket(src, dst, 1, 443, 1, 1, TCPFlagAck, nil, 64, prev, false) + if id := uint16(pkt[4])<<8 | uint16(pkt[5]); id != prev { + t.Fatalf("IP ID = %d, want %d", id, prev) + } + } +} diff --git a/transport/internet/finalmask/rawpacket/spoof_transport.go b/transport/internet/finalmask/rawpacket/spoof_transport.go new file mode 100644 index 000000000000..116e07cbc4f5 --- /dev/null +++ b/transport/internet/finalmask/rawpacket/spoof_transport.go @@ -0,0 +1,69 @@ +package rawpacket + +import "net/netip" + +type SpoofSender interface { + Send(payload []byte, dstIP netip.Addr, dstPort uint16, tcp *TCPSimState) error + Close() error +} + +// TCPMeta carries the header fields of a received raw packet so the +// caller can keep the fake conversation's sequence/ack state plausible, +// and the relay can masquerade replies from the address the probe dialed. +// DstIP/DstPort are always set; Seq/Flags are non-zero only for TCP. +// nil for transports the receiver does not describe (ICMP). +type TCPMeta struct { + Seq uint32 + Flags uint8 + DstIP netip.Addr + DstPort uint16 +} + +type SpoofReceiver interface { + Receive() (payload []byte, srcIP netip.Addr, srcPort uint16, tcp *TCPMeta, err error) + Close() error +} + +func NewSender(transport string, cfg *SpoofSenderConfig) (SpoofSender, error) { + switch transport { + case "tcp", "": + return newTCPSender(cfg) + case "udp": + return newUDPSender(cfg) + case "icmp": + return newICMPSender(cfg) + case "icmpv6": + return newICMPv6Sender(cfg) + } + return nil, nil +} + +func NewReceiver(transport string, cfg *SpoofReceiverConfig) (SpoofReceiver, error) { + switch transport { + case "tcp", "": + return newTCPReceiver(cfg) + case "udp": + return newUDPReceiver(cfg) + case "icmp": + return newICMPReceiver(cfg) + case "icmpv6": + return newICMPv6Receiver(cfg) + } + return nil, nil +} + +type SpoofSenderConfig struct { + SourceIP netip.Addr + SourceIPs []netip.Addr + SourcePort uint16 + TTL uint8 + // Server marks a relay-side sender: outbound TCP segments take the + // passive-opener role (SYN|ACK then ACK). + Server bool +} + +type SpoofReceiverConfig struct { + ListenPort uint16 + PeerSpoofIP netip.Addr + BufferSize int +} diff --git a/transport/internet/finalmask/rawpacket/tcp_state.go b/transport/internet/finalmask/rawpacket/tcp_state.go new file mode 100644 index 000000000000..a8ad3014363f --- /dev/null +++ b/transport/internet/finalmask/rawpacket/tcp_state.go @@ -0,0 +1,118 @@ +package rawpacket + +import ( + "math/rand" + "sync" + "time" +) + +// TCPSimState simulates a plausible TCP conversation between the client +// and the relay so middleboxes see a normal connection: SYN with TCP +// options, then ACK segments with monotonically increasing sequence +// numbers and correct acknowledgements. +// +// The client and the relay each keep one state per tunnel session. +// The client is the "active opener" (sends SYN, then ACKs), the relay is +// the "passive opener" (replies SYN|ACK, then ACKs). Which role a state +// plays is decided by the first outbound segment: client role sends a +// bare SYN, server role sends SYN|ACK. +type TCPSimState struct { + mu sync.Mutex + isn uint32 // our initial sequence number + seq uint32 // next sequence number to send + synSent bool // our SYN (or SYN|ACK) has been sent + peerISN uint32 // peer's initial sequence number + peerSeq uint32 // peer's next expected sequence number (peer's last seq + 1) + peerSeen bool +} + +func newTCPSimState() *TCPSimState { + isn := uint32(rand.Int63n(1 << 31)) + return &TCPSimState{isn: isn, seq: isn} +} + +// nextSeq returns the sequence number to use for an outbound segment of +// the given payload length and advances the counter. Zero-length segments +// (keepalives) do not consume sequence numbers. +func (s *TCPSimState) nextSeq(payloadLen int) uint32 { + s.mu.Lock() + defer s.mu.Unlock() + seq := s.seq + if payloadLen > 0 { + s.seq += uint32(payloadLen) + } + return seq +} + +// flags returns the flags for the next outbound segment in client role. +func (s *TCPSimState) clientFlags() uint8 { + s.mu.Lock() + defer s.mu.Unlock() + if !s.synSent { + s.synSent = true + return TCPFlagSyn + } + return TCPFlagAck +} + +// flags returns the flags for the next outbound segment in server role. +func (s *TCPSimState) serverFlags() uint8 { + s.mu.Lock() + defer s.mu.Unlock() + if !s.synSent { + s.synSent = true + return TCPFlagSyn | TCPFlagAck + } + return TCPFlagAck +} + +// ack returns the acknowledgement number for the next outbound segment: +// the peer's last seen sequence number plus one, or zero before the peer +// is seen. +func (s *TCPSimState) ack() uint32 { + s.mu.Lock() + defer s.mu.Unlock() + if !s.peerSeen { + return 0 + } + return s.peerSeq +} + +// observePeer records the peer's latest segment (its wire sequence number +// and payload length) so outbound acknowledgements stay plausible. The +// first segment is the peer's SYN and consumes one byte; later segments +// advance by their payload length only. +func (s *TCPSimState) observePeer(seq uint32, payloadLen int) { + s.mu.Lock() + defer s.mu.Unlock() + if !s.peerSeen { + s.peerSeen = true + s.peerISN = seq + s.peerSeq = seq + 1 + uint32(payloadLen) + return + } + s.peerSeq = seq + uint32(payloadLen) +} + +// observeClientSeq records the client's latest wire sequence number so +// server-role acknowledgements are correct. Used on the relay, where the +// client's cumulative sequence is already encoded in the wire seq. The +// first segment (the client's SYN) consumes one byte; later segments +// advance by their payload length only. +func (s *TCPSimState) observeClientSeq(seq uint32, payloadLen int) { + s.mu.Lock() + defer s.mu.Unlock() + if !s.peerSeen { + s.peerSeen = true + s.peerISN = seq + s.peerSeq = seq + 1 + uint32(payloadLen) + return + } + s.peerSeq = seq + uint32(payloadLen) +} + +// tsVal returns a plausible TCP timestamp value: milliseconds since a +// fixed epoch, so it grows monotonically like Linux jiffies. +func tsVal() uint32 { + return uint32(time.Now().UnixMilli() & 0xFFFFFFFF) +} diff --git a/transport/internet/finalmask/rawpacket/tcpip.go b/transport/internet/finalmask/rawpacket/tcpip.go new file mode 100644 index 000000000000..bd00a28c0112 --- /dev/null +++ b/transport/internet/finalmask/rawpacket/tcpip.go @@ -0,0 +1,196 @@ +package rawpacket + +import ( + "encoding/binary" + "net/netip" +) + +const ( + IPv4MinimumSize = 20 + IPv6MinimumSize = 40 + TCPMinimumSize = 20 + TCPProtocolNumber = 6 + + TCPOptionEOL = 0 + TCPOptionNOP = 1 + TCPOptionTS = 8 + TCPOptionTSLength = 10 + + TCPFlagFin = 0x01 + TCPFlagSyn = 0x02 + TCPFlagRst = 0x04 + TCPFlagPsh = 0x08 + TCPFlagAck = 0x10 +) + +func Checksum(data []byte, initial uint16) uint16 { + var csum uint32 = uint32(initial) + for i := 0; i < len(data)-1; i += 2 { + csum += uint32(binary.BigEndian.Uint16(data[i:])) + } + if len(data)%2 == 1 { + csum += uint32(data[len(data)-1]) << 8 + } + for csum > 0xffff { + csum = (csum >> 16) + (csum & 0xffff) + } + return uint16(csum) +} + +func PseudoHeaderChecksum(protocol uint8, srcAddr, dstAddr []byte, totalLen uint16) uint16 { + var csum uint32 + for i := 0; i < len(srcAddr); i += 2 { + csum += uint32(binary.BigEndian.Uint16(srcAddr[i:])) + } + for i := 0; i < len(dstAddr); i += 2 { + csum += uint32(binary.BigEndian.Uint16(dstAddr[i:])) + } + csum += uint32(protocol) + csum += uint32(totalLen) + for csum > 0xffff { + csum = (csum >> 16) + (csum & 0xffff) + } + return uint16(csum) +} + +func CombineChecksum(c1, c2 uint16) uint16 { + csum := uint32(c1) + uint32(c2) + for csum > 0xffff { + csum = (csum >> 16) + (csum & 0xffff) + } + return uint16(csum) +} + +func EncodeTSOption(val uint32, ecr uint32, b []byte) { + b[0] = TCPOptionTS + b[1] = TCPOptionTSLength + binary.BigEndian.PutUint32(b[2:], val) + binary.BigEndian.PutUint32(b[6:], ecr) +} + +func ParseTCPOptions(b []byte) (tsVal uint32, hasTS bool) { + for i := 0; i < len(b); { + if b[i] == TCPOptionEOL { + break + } + if b[i] == TCPOptionNOP { + i++ + continue + } + if i+1 >= len(b) { + break + } + optLen := int(b[i+1]) + if optLen < 2 || i+optLen > len(b) { + break + } + if b[i] == TCPOptionTS && optLen == TCPOptionTSLength { + return binary.BigEndian.Uint32(b[i+2:]), true + } + i += optLen + } + return 0, false +} + +// IPv4 header representation +type IPv4 []byte + +func (b IPv4) TotalLength() uint16 { return binary.BigEndian.Uint16(b[2:]) } +func (b IPv4) Flags() uint8 { return uint8(binary.BigEndian.Uint16(b[6:]) >> 13) } +func (b IPv4) FragmentOffset() uint16 { return binary.BigEndian.Uint16(b[6:]) & 0x1fff } +func (b IPv4) Protocol() uint8 { return b[9] } +func (b IPv4) HeaderLength() uint8 { return (b[0] & 0x0f) * 4 } +func (b IPv4) ID() uint16 { return binary.BigEndian.Uint16(b[4:]) } +func (b IPv4) Src() netip.Addr { return netip.AddrFrom4([4]byte(b[12:16])) } +func (b IPv4) Dst() netip.Addr { return netip.AddrFrom4([4]byte(b[16:20])) } + +func (b IPv4) SetID(id uint16) { + binary.BigEndian.PutUint16(b[4:], id) +} + +func (b IPv4) SetTotalLength(n uint16) { + binary.BigEndian.PutUint16(b[2:], n) +} + +func (b IPv4) RecalcChecksum() { + binary.BigEndian.PutUint16(b[10:], 0) + csum := Checksum(b[:20], 0) + binary.BigEndian.PutUint16(b[10:], ^csum) +} + +func (b IPv4) Encode(totalLength uint16, id uint16, ttl uint8, protocol uint8, src, dst netip.Addr) { + b[0] = (4 << 4) | 5 // IPv4, Header Length = 20 + b[1] = 0 // TOS + binary.BigEndian.PutUint16(b[2:], totalLength) + binary.BigEndian.PutUint16(b[4:], id) + binary.BigEndian.PutUint16(b[6:], 0) // Flags and Fragment Offset + b[8] = ttl + b[9] = protocol + b[10] = 0 // Checksum (0 for calculation) + copy(b[12:16], src.AsSlice()) + copy(b[16:20], dst.AsSlice()) + csum := Checksum(b[:20], 0) + binary.BigEndian.PutUint16(b[10:], ^csum) +} + +type IPv6 []byte + +func (b IPv6) PayloadLength() uint16 { return binary.BigEndian.Uint16(b[4:]) } +func (b IPv6) TransportProtocol() uint8 { return b[6] } +func (b IPv6) Src() netip.Addr { return netip.AddrFrom16([16]byte(b[8:24])) } +func (b IPv6) Dst() netip.Addr { return netip.AddrFrom16([16]byte(b[24:40])) } + +func (b IPv6) SetPayloadLength(n uint16) { + binary.BigEndian.PutUint16(b[4:], n) +} + +func (b IPv6) Encode(payloadLength uint16, transportProtocol uint8, hopLimit uint8, src, dst netip.Addr) { + binary.BigEndian.PutUint32(b[0:], 6<<28) // Version 6, Traffic Class 0, Flow Label 0 + binary.BigEndian.PutUint16(b[4:], payloadLength) + b[6] = transportProtocol + b[7] = hopLimit + copy(b[8:24], src.AsSlice()) + copy(b[24:40], dst.AsSlice()) +} + +type TCP []byte + +func (b TCP) DataOffset() uint8 { return (b[12] >> 4) * 4 } +func (b TCP) SequenceNumber() uint32 { return binary.BigEndian.Uint32(b[4:]) } +func (b TCP) AckNumber() uint32 { return binary.BigEndian.Uint32(b[8:]) } +func (b TCP) Flags() uint8 { return b[13] } +func (b TCP) WindowSize() uint16 { return binary.BigEndian.Uint16(b[14:]) } +func (b TCP) Options() []byte { return b[TCPMinimumSize:b.DataOffset()] } +func (b TCP) SetChecksum(csum uint16) { binary.BigEndian.PutUint16(b[16:], csum) } + +func (b TCP) SetSequenceNumber(seq uint32) { + binary.BigEndian.PutUint32(b[4:], seq) +} + +func (b TCP) SetAckNumber(ack uint32) { + binary.BigEndian.PutUint32(b[8:], ack) +} + +func (b TCP) SetFlags(flags uint8) { + b[13] = flags +} + +func (b TCP) SetWindowSize(wind uint16) { + binary.BigEndian.PutUint16(b[14:], wind) +} + +func (b TCP) Encode(srcPort, dstPort uint16, seqNum, ackNum uint32, dataOffset uint8, flags uint8, windowSize uint16) { + binary.BigEndian.PutUint16(b[0:], srcPort) + binary.BigEndian.PutUint16(b[2:], dstPort) + binary.BigEndian.PutUint32(b[4:], seqNum) + binary.BigEndian.PutUint32(b[8:], ackNum) + b[12] = (dataOffset / 4) << 4 + b[13] = flags + binary.BigEndian.PutUint16(b[14:], windowSize) + b[16] = 0 // Checksum + binary.BigEndian.PutUint16(b[18:], 0) // Urgent pointer +} + +func (b TCP) CalculateChecksum(initial uint16) uint16 { + return Checksum(b, initial) +} diff --git a/transport/internet/finalmask/rawpacket/windivert/assets/LICENSE.txt b/transport/internet/finalmask/rawpacket/windivert/assets/LICENSE.txt new file mode 100644 index 000000000000..8489a8e773c3 --- /dev/null +++ b/transport/internet/finalmask/rawpacket/windivert/assets/LICENSE.txt @@ -0,0 +1,1191 @@ +WinDivert is dual-licensed under your choice of the GNU Lesser General Public +License (LGPL) Version 3 or the GNU General Public License (GPL) Version 2. +Copies of the LGPLv3, GPLv3 and GPLv2 are provided below. + +============================================================================== + + GNU LESSER GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + + This version of the GNU Lesser General Public License incorporates +the terms and conditions of version 3 of the GNU General Public +License, supplemented by the additional permissions listed below. + + 0. Additional Definitions. + + As used herein, "this License" refers to version 3 of the GNU Lesser +General Public License, and the "GNU GPL" refers to version 3 of the GNU +General Public License. + + "The Library" refers to a covered work governed by this License, +other than an Application or a Combined Work as defined below. + + An "Application" is any work that makes use of an interface provided +by the Library, but which is not otherwise based on the Library. +Defining a subclass of a class defined by the Library is deemed a mode +of using an interface provided by the Library. + + A "Combined Work" is a work produced by combining or linking an +Application with the Library. The particular version of the Library +with which the Combined Work was made is also called the "Linked +Version". + + The "Minimal Corresponding Source" for a Combined Work means the +Corresponding Source for the Combined Work, excluding any source code +for portions of the Combined Work that, considered in isolation, are +based on the Application, and not on the Linked Version. + + The "Corresponding Application Code" for a Combined Work means the +object code and/or source code for the Application, including any data +and utility programs needed for reproducing the Combined Work from the +Application, but excluding the System Libraries of the Combined Work. + + 1. Exception to Section 3 of the GNU GPL. + + You may convey a covered work under sections 3 and 4 of this License +without being bound by section 3 of the GNU GPL. + + 2. Conveying Modified Versions. + + If you modify a copy of the Library, and, in your modifications, a +facility refers to a function or data to be supplied by an Application +that uses the facility (other than as an argument passed when the +facility is invoked), then you may convey a copy of the modified +version: + + a) under this License, provided that you make a good faith effort to + ensure that, in the event an Application does not supply the + function or data, the facility still operates, and performs + whatever part of its purpose remains meaningful, or + + b) under the GNU GPL, with none of the additional permissions of + this License applicable to that copy. + + 3. Object Code Incorporating Material from Library Header Files. + + The object code form of an Application may incorporate material from +a header file that is part of the Library. You may convey such object +code under terms of your choice, provided that, if the incorporated +material is not limited to numerical parameters, data structure +layouts and accessors, or small macros, inline functions and templates +(ten or fewer lines in length), you do both of the following: + + a) Give prominent notice with each copy of the object code that the + Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the object code with a copy of the GNU GPL and this license + document. + + 4. Combined Works. + + You may convey a Combined Work under terms of your choice that, +taken together, effectively do not restrict modification of the +portions of the Library contained in the Combined Work and reverse +engineering for debugging such modifications, if you also do each of +the following: + + a) Give prominent notice with each copy of the Combined Work that + the Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the Combined Work with a copy of the GNU GPL and this license + document. + + c) For a Combined Work that displays copyright notices during + execution, include the copyright notice for the Library among + these notices, as well as a reference directing the user to the + copies of the GNU GPL and this license document. + + d) Do one of the following: + + 0) Convey the Minimal Corresponding Source under the terms of this + License, and the Corresponding Application Code in a form + suitable for, and under terms that permit, the user to + recombine or relink the Application with a modified version of + the Linked Version to produce a modified Combined Work, in the + manner specified by section 6 of the GNU GPL for conveying + Corresponding Source. + + 1) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (a) uses at run time + a copy of the Library already present on the user's computer + system, and (b) will operate properly with a modified version + of the Library that is interface-compatible with the Linked + Version. + + e) Provide Installation Information, but only if you would otherwise + be required to provide such information under section 6 of the + GNU GPL, and only to the extent that such information is + necessary to install and execute a modified version of the + Combined Work produced by recombining or relinking the + Application with a modified version of the Linked Version. (If + you use option 4d0, the Installation Information must accompany + the Minimal Corresponding Source and Corresponding Application + Code. If you use option 4d1, you must provide the Installation + Information in the manner specified by section 6 of the GNU GPL + for conveying Corresponding Source.) + + 5. Combined Libraries. + + You may place library facilities that are a work based on the +Library side by side in a single library together with other library +facilities that are not Applications and are not covered by this +License, and convey such a combined library under terms of your +choice, if you do both of the following: + + a) Accompany the combined library with a copy of the same work based + on the Library, uncombined with any other library facilities, + conveyed under the terms of this License. + + b) Give prominent notice with the combined library that part of it + is a work based on the Library, and explaining where to find the + accompanying uncombined form of the same work. + + 6. Revised Versions of the GNU Lesser General Public License. + + The Free Software Foundation may publish revised and/or new versions +of the GNU Lesser General Public License from time to time. Such new +versions will be similar in spirit to the present version, but may +differ in detail to address new problems or concerns. + + Each version is given a distinguishing version number. If the +Library as you received it specifies that a certain numbered version +of the GNU Lesser General Public License "or any later version" +applies to it, you have the option of following the terms and +conditions either of that published version or of any later version +published by the Free Software Foundation. If the Library as you +received it does not specify a version number of the GNU Lesser +General Public License, you may choose any version of the GNU Lesser +General Public License ever published by the Free Software Foundation. + + If the Library as you received it specifies that a proxy can decide +whether future versions of the GNU Lesser General Public License shall +apply, that proxy's public statement of acceptance of any version is +permanent authorization for you to choose that version for the +Library. + +============================================================================== + + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. + +============================================================================== + + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. + diff --git a/transport/internet/finalmask/rawpacket/windivert/assets/WinDivert32.sys b/transport/internet/finalmask/rawpacket/windivert/assets/WinDivert32.sys new file mode 100644 index 000000000000..d06738cbb783 Binary files /dev/null and b/transport/internet/finalmask/rawpacket/windivert/assets/WinDivert32.sys differ diff --git a/transport/internet/finalmask/rawpacket/windivert/assets/WinDivert64.sys b/transport/internet/finalmask/rawpacket/windivert/assets/WinDivert64.sys new file mode 100644 index 000000000000..218ccaf423ef Binary files /dev/null and b/transport/internet/finalmask/rawpacket/windivert/assets/WinDivert64.sys differ diff --git a/transport/internet/finalmask/rawpacket/windivert/assets_386.go b/transport/internet/finalmask/rawpacket/windivert/assets_386.go new file mode 100644 index 000000000000..0cbf35ed5cbf --- /dev/null +++ b/transport/internet/finalmask/rawpacket/windivert/assets_386.go @@ -0,0 +1,14 @@ +//go:build windows && 386 + +package windivert + +import _ "embed" + +//go:embed assets/WinDivert32.sys +var sysBytes []byte + +func assetFiles() []assetFile { + return []assetFile{{"WinDivert32.sys", sysBytes}} +} + +func driverSysName() string { return "WinDivert32.sys" } diff --git a/transport/internet/finalmask/rawpacket/windivert/assets_amd64.go b/transport/internet/finalmask/rawpacket/windivert/assets_amd64.go new file mode 100644 index 000000000000..2c9fb6c6ad19 --- /dev/null +++ b/transport/internet/finalmask/rawpacket/windivert/assets_amd64.go @@ -0,0 +1,14 @@ +//go:build windows && amd64 + +package windivert + +import _ "embed" + +//go:embed assets/WinDivert64.sys +var sysBytes []byte + +func assetFiles() []assetFile { + return []assetFile{{"WinDivert64.sys", sysBytes}} +} + +func driverSysName() string { return "WinDivert64.sys" } diff --git a/transport/internet/finalmask/rawpacket/windivert/assets_unsupported.go b/transport/internet/finalmask/rawpacket/windivert/assets_unsupported.go new file mode 100644 index 000000000000..04698953fa6b --- /dev/null +++ b/transport/internet/finalmask/rawpacket/windivert/assets_unsupported.go @@ -0,0 +1,7 @@ +//go:build windows && !amd64 && !386 + +package windivert + +func assetFiles() []assetFile { return nil } + +func driverSysName() string { return "" } diff --git a/transport/internet/finalmask/rawpacket/windivert/driver_windows.go b/transport/internet/finalmask/rawpacket/windivert/driver_windows.go new file mode 100644 index 000000000000..50e94c578422 --- /dev/null +++ b/transport/internet/finalmask/rawpacket/windivert/driver_windows.go @@ -0,0 +1,211 @@ +//go:build windows + +package windivert + +import ( + "errors" + "fmt" + "os" + "path/filepath" + "runtime" + "strconv" + "sync" + + "golang.org/x/sys/windows" +) + +const ( + driverServiceName = "WinDivert" + driverDeviceName = `\\.\WinDivert` +) + +var ( + driverOnce sync.Once + driverErr error + // driverDevName is ASCII-safe and must be available before ensureDriver + // so Open can try CreateFile first and only install on FILE_NOT_FOUND. + driverDevName, _ = windows.UTF16PtrFromString(driverDeviceName) +) + +// Requires SeLoadDriverPrivilege (Administrator). Running the 386 build +// under WOW64 on a 64-bit kernel is rejected — use the amd64 build. +func ensureDriver() error { + driverOnce.Do(func() { + driverErr = installDriver() + }) + return driverErr +} + +func installDriver() error { + if runtime.GOARCH == "386" { + var isWow64 bool + err := windows.IsWow64Process(windows.CurrentProcess(), &isWow64) + if err == nil && isWow64 { + return errors.New("windivert: 386 build detected running under WOW64 on a 64-bit kernel; use the amd64 build") + } + } + + dir, err := ensureExtracted() + if err != nil { + return err + } + sysPath := filepath.Join(dir, driverSysName()) + sysPathW, err := windows.UTF16PtrFromString(sysPath) + if err != nil { + return fmt.Errorf("windivert: utf16 driver path: %w", err) + } + + // Serialize driver install across concurrent processes. + mutexName, _ := windows.UTF16PtrFromString("WinDivertDriverInstallMutex") + mutex, err := windows.CreateMutex(nil, false, mutexName) + if err != nil { + return fmt.Errorf("windivert: create install mutex: %w", err) + } + defer windows.CloseHandle(mutex) + _, err = windows.WaitForSingleObject(mutex, windows.INFINITE) + if err != nil { + return fmt.Errorf("windivert: wait install mutex: %w", err) + } + defer windows.ReleaseMutex(mutex) + + manager, err := windows.OpenSCManager(nil, nil, windows.SC_MANAGER_ALL_ACCESS) + if err != nil { + return fmt.Errorf("windivert: open SCM: %w", err) + } + defer windows.CloseServiceHandle(manager) + + serviceNameW, _ := windows.UTF16PtrFromString(driverServiceName) + service, err := windows.OpenService(manager, serviceNameW, windows.SERVICE_ALL_ACCESS) + if err != nil { + service, err = windows.CreateService( + manager, + serviceNameW, + serviceNameW, + windows.SERVICE_ALL_ACCESS, + windows.SERVICE_KERNEL_DRIVER, + windows.SERVICE_DEMAND_START, + windows.SERVICE_ERROR_NORMAL, + sysPathW, + nil, nil, nil, nil, nil, + ) + if err != nil { + if errors.Is(err, windows.ERROR_SERVICE_EXISTS) { + service, err = windows.OpenService(manager, serviceNameW, windows.SERVICE_ALL_ACCESS) + } + if err != nil { + return wrapDriverInstallError(err) + } + } + } + defer windows.CloseServiceHandle(service) + + err = windows.StartService(service, 0, nil) + if err != nil && errors.Is(err, windows.ERROR_SERVICE_DISABLED) { + // A prior process called DeleteService on a still-running kernel + // driver: SCM marks the record for deletion and flips START_TYPE + // to DISABLED until the last handle closes. Re-enable so we can + // start it instead of waiting for a reboot. + err = windows.ChangeServiceConfig( + service, + windows.SERVICE_NO_CHANGE, + windows.SERVICE_DEMAND_START, + windows.SERVICE_NO_CHANGE, + nil, nil, nil, nil, nil, nil, nil, + ) + if err != nil { + return fmt.Errorf("windivert: re-enable disabled service: %w", err) + } + err = windows.StartService(service, 0, nil) + } + if err == nil { + // Mark for deletion so the driver unregisters when the last handle + // closes or on next reboot. Matches the upstream DLL's behavior: + // only the process that actually started the service takes on the + // cleanup responsibility. If another process already started it, + // we leave DeleteService to them. + _ = windows.DeleteService(service) + } else if !errors.Is(err, windows.ERROR_SERVICE_ALREADY_RUNNING) { + return fmt.Errorf("windivert: start service: %w", err) + } + return nil +} + +func wrapDriverInstallError(err error) error { + if errors.Is(err, windows.ERROR_ACCESS_DENIED) { + return fmt.Errorf("windivert: installing the kernel driver requires Administrator privileges: %w", err) + } + return fmt.Errorf("windivert: create service: %w", err) +} + +type assetFile struct { + name string + data []byte +} + +var ( + extractOnce sync.Once + extractErr error + extractDir string +) + +// The on-disk copy is protected by Windows Authenticode signature +// enforcement, which rejects any tampered .sys at StartService time. +func ensureExtracted() (string, error) { + extractOnce.Do(func() { + extractDir, extractErr = extractImpl() + }) + return extractDir, extractErr +} + +func extractImpl() (string, error) { + files := assetFiles() + if len(files) == 0 { + return "", fmt.Errorf("windivert: unsupported architecture %s", runtime.GOARCH) + } + + base, err := os.UserCacheDir() + if err != nil { + return "", fmt.Errorf("windivert: locate user cache dir: %w", err) + } + dir := filepath.Join(base, "xray-core", "windivert", "v"+AssetVersion) + err = os.MkdirAll(dir, 0o755) + if err != nil { + return "", fmt.Errorf("windivert: mkdir %s: %w", dir, err) + } + + for _, asset := range files { + err = ensureAsset(dir, asset) + if err != nil { + return "", err + } + } + return dir, nil +} + +// Concurrent sing-box processes race on os.Rename (atomic on NTFS); +// whichever wins creates the final file. Writers that lose the race +// silently discard their temp copy. +func ensureAsset(dir string, asset assetFile) error { + target := filepath.Join(dir, asset.name) + _, err := os.Stat(target) + if err == nil { + return nil + } + if !os.IsNotExist(err) { + return fmt.Errorf("windivert: stat %s: %w", asset.name, err) + } + tmp := target + ".tmp-" + strconv.Itoa(os.Getpid()) + err = os.WriteFile(tmp, asset.data, 0o644) + if err != nil { + return fmt.Errorf("windivert: write %s: %w", asset.name, err) + } + err = os.Rename(tmp, target) + if err != nil { + os.Remove(tmp) + if _, statErr := os.Stat(target); statErr == nil { + return nil + } + return fmt.Errorf("windivert: rename %s: %w", asset.name, err) + } + return nil +} diff --git a/transport/internet/finalmask/rawpacket/windivert/filter.go b/transport/internet/finalmask/rawpacket/windivert/filter.go new file mode 100644 index 000000000000..fbc58b9c0e08 --- /dev/null +++ b/transport/internet/finalmask/rawpacket/windivert/filter.go @@ -0,0 +1,199 @@ +package windivert + +import ( + "encoding/binary" + "errors" + "net/netip" +) + +// WINDIVERT_FILTER VM instruction layout (24 bytes, #pragma pack(1)): +// +// word 0 (LE): field:11 | test:5 | success:16 +// word 1 (LE): failure:16 | neg:1 | reserved:15 +// words 2..5: arg[4] (native-endian uint32 each) +// +// The driver walks this as a decision tree: evaluate the test at inst i; +// on success jump to success; on failure jump to failure. Continuations +// 0x7FFE and 0x7FFF are ACCEPT and REJECT terminals. +const ( + filterInstBytes = 24 + filterMaxInsts = 256 + + fieldZero = 0 + fieldOutbound = 2 + fieldIP = 5 + fieldIPv6 = 6 + fieldTCP = 8 + fieldIPSrcAddr = 21 + fieldIPDstAddr = 22 + fieldIPv6SrcAddr = 28 + fieldIPv6DstAddr = 29 + fieldTCPSrcPort = 38 + fieldTCPDstPort = 39 + + testEQ = 0 + + resultAccept uint16 = 0x7FFE + resultReject uint16 = 0x7FFF +) + +// Filter flags passed to IOCTL_WINDIVERT_STARTUP alongside the compiled +// filter. These tell the driver what *kinds* of packets the filter might +// match, used as a kernel-side fast-reject. +const ( + filterFlagOutbound uint64 = 0x0020 + filterFlagIP uint64 = 0x0040 + filterFlagIPv6 uint64 = 0x0080 +) + +type filterInst struct { + field uint16 // 11 bits used + test uint8 // 5 bits used + success uint16 + failure uint16 + neg bool + arg [4]uint32 +} + +// Filter is a typed specification of packets to capture. It replaces +// WinDivert's filter string language. +// +// Zero value = "reject all" (match nothing), suitable for send-only handles. +type Filter struct { + insts []filterInst + flags uint64 // filter flags for STARTUP ioctl +} + +// reject returns a filter that matches no packet. The empty insts slice +// is encoded as a single rejecting instruction by encode(). +func reject() *Filter { + return &Filter{} +} + +// AcceptAll returns a filter that matches every network-layer packet. +// Suitable for sniffing handles that filter in userspace. All filter +// flags are set since the filter may match any packet class. +func AcceptAll() *Filter { + f := &Filter{flags: filterFlagOutbound | filterFlagIP | filterFlagIPv6} + f.add(fieldZero, testEQ, argUint32(0)) + return f +} + +// OutboundTCP returns a filter matching outbound TCP packets on the given +// 5-tuple. Both addresses must share an address family (IPv4 or IPv6). +func OutboundTCP(src, dst netip.AddrPort) (*Filter, error) { + return tcpFilter(src, dst, true) +} + +// BidirectionalTCP returns a filter matching TCP packets in either direction +// on the given 5-tuple. Both addresses must share an address family. +func BidirectionalTCP(src, dst netip.AddrPort) (*Filter, error) { + return tcpFilter(src, dst, false) +} + +func tcpFilter(src, dst netip.AddrPort, outboundOnly bool) (*Filter, error) { + if !src.IsValid() || !dst.IsValid() { + return nil, errors.New("windivert: filter: invalid address port") + } + if src.Addr().Is4() != dst.Addr().Is4() { + return nil, errors.New("windivert: filter: mixed IPv4/IPv6") + } + f := &Filter{} + if outboundOnly { + f.flags = filterFlagOutbound + f.add(fieldOutbound, testEQ, argUint32(1)) + } + if src.Addr().Is4() { + f.flags |= filterFlagIP + f.add(fieldIP, testEQ, argUint32(1)) + f.add(fieldTCP, testEQ, argUint32(1)) + f.add(fieldIPSrcAddr, testEQ, argIPv4(src.Addr())) + f.add(fieldIPDstAddr, testEQ, argIPv4(dst.Addr())) + } else { + f.flags |= filterFlagIPv6 + f.add(fieldIPv6, testEQ, argUint32(1)) + f.add(fieldTCP, testEQ, argUint32(1)) + f.add(fieldIPv6SrcAddr, testEQ, argIPv6(src.Addr())) + f.add(fieldIPv6DstAddr, testEQ, argIPv6(dst.Addr())) + } + f.add(fieldTCPSrcPort, testEQ, argUint32(uint32(src.Port()))) + f.add(fieldTCPDstPort, testEQ, argUint32(uint32(dst.Port()))) + return f, nil +} + +func (f *Filter) add(field uint16, test uint8, arg [4]uint32) { + f.insts = append(f.insts, filterInst{field: field, test: test, arg: arg}) +} + +func argUint32(v uint32) [4]uint32 { return [4]uint32{v, 0, 0, 0} } + +// argIPv4 encodes an IPv4 address for IP_SRCADDR/IP_DSTADDR. The driver +// compares against an IPv4-mapped-IPv6 form: {host_order_u32, 0x0000FFFF, +// 0, 0} (see sys/windivert.c windivert_get_ipv4_addr and the IPv4_SRCADDR +// val-word construction). Omitting the 0x0000FFFF marker causes the EQ +// test to fail for every packet. +func argIPv4(addr netip.Addr) [4]uint32 { + b := addr.As4() + return [4]uint32{binary.BigEndian.Uint32(b[:]), 0x0000FFFF, 0, 0} +} + +// argIPv6 encodes an IPv6 address for IPV6_SRCADDR/IPV6_DSTADDR. The +// driver stores the address as four host-order uint32s in REVERSED word +// order: val[0]=low (bytes 12..15), val[3]=high (bytes 0..3). See +// sys/windivert.c windivert_outbound_network_v6_classify val-word +// construction. +func argIPv6(addr netip.Addr) [4]uint32 { + b := addr.As16() + return [4]uint32{ + binary.BigEndian.Uint32(b[12:16]), + binary.BigEndian.Uint32(b[8:12]), + binary.BigEndian.Uint32(b[4:8]), + binary.BigEndian.Uint32(b[0:4]), + } +} + +// encode serializes the Filter to the on-wire WINDIVERT_FILTER[] format +// plus the filter_flags for STARTUP ioctl. +func (f *Filter) encode() ([]byte, uint64, error) { + if len(f.insts) == 0 { + // "Reject all" — one instruction, ZERO == 0 is always true, but we + // invert by setting both success and failure to REJECT. + return encodeInst(filterInst{ + field: fieldZero, + test: testEQ, + success: resultReject, + failure: resultReject, + }), 0, nil + } + if len(f.insts) > filterMaxInsts-1 { + return nil, 0, errors.New("windivert: filter too long") + } + buf := make([]byte, 0, filterInstBytes*len(f.insts)) + for i, inst := range f.insts { + if i == len(f.insts)-1 { + inst.success = resultAccept + } else { + inst.success = uint16(i + 1) + } + inst.failure = resultReject + buf = append(buf, encodeInst(inst)...) + } + return buf, f.flags, nil +} + +func encodeInst(inst filterInst) []byte { + out := make([]byte, filterInstBytes) + word0 := uint32(inst.field&0x7FF) | uint32(inst.test&0x1F)<<11 | + uint32(inst.success)<<16 + word1 := uint32(inst.failure) + if inst.neg { + word1 |= 1 << 16 + } + binary.LittleEndian.PutUint32(out[0:4], word0) + binary.LittleEndian.PutUint32(out[4:8], word1) + binary.LittleEndian.PutUint32(out[8:12], inst.arg[0]) + binary.LittleEndian.PutUint32(out[12:16], inst.arg[1]) + binary.LittleEndian.PutUint32(out[16:20], inst.arg[2]) + binary.LittleEndian.PutUint32(out[20:24], inst.arg[3]) + return out +} diff --git a/transport/internet/finalmask/rawpacket/windivert/handle_windows.go b/transport/internet/finalmask/rawpacket/windivert/handle_windows.go new file mode 100644 index 000000000000..c48e6214c11b --- /dev/null +++ b/transport/internet/finalmask/rawpacket/windivert/handle_windows.go @@ -0,0 +1,323 @@ +//go:build windows + +package windivert + +import ( + "encoding/binary" + "errors" + "fmt" + "runtime" + "sync" + "unsafe" + + "golang.org/x/sys/windows" +) + +// Handle owns a WinDivert kernel device handle plus a private event for +// overlapped I/O. Methods on *Handle are not safe for concurrent use +// across goroutines (there is a single shared event per Handle). +// +// addr is a per-Handle Address buffer the IOCTL struct embeds a pointer +// to. It lives on the heap (as a field of a heap-allocated Handle) so +// the pointer value stored as bytes in the ioctl buffer remains valid +// across stack growth between buildIoctl* and the DeviceIoControl +// syscall — stack-local Address values are not safe for this pattern +// because Go's escape analysis does not see the pointer through the +// unsafe.Pointer → uintptr → bytes conversion. +type Handle struct { + device windows.Handle + event windows.Handle + closing sync.Once + closeErr error + addr Address +} + +// Filter may be nil for "reject all", suitable for send-only handles. +// Requires Administrator on first call per process (installs the kernel +// driver via SCM); subsequent calls reuse the running driver. +func Open(filter *Filter, layer Layer, priority int16, flags Flag) (*Handle, error) { + err := validateOpenArgs(layer, priority, flags) + if err != nil { + return nil, err + } + if filter == nil { + filter = reject() + } + filterBin, filterFlags, err := filter.encode() + if err != nil { + return nil, err + } + device, err := openDevice() + if err != nil { + if !errors.Is(err, windows.ERROR_FILE_NOT_FOUND) && + !errors.Is(err, windows.ERROR_PATH_NOT_FOUND) { + if errors.Is(err, windows.ERROR_ACCESS_DENIED) { + return nil, fmt.Errorf("windivert: open device (administrator required): %w", err) + } + return nil, fmt.Errorf("windivert: open device: %w", err) + } + // Device node missing: kernel driver not loaded. Install + retry. + // Matches WinDivertOpen's lazy-install path; avoids racing StartService + // against a still-loaded driver whose SCM record is marked for deletion. + err = ensureDriver() + if err != nil { + return nil, err + } + device, err = openDevice() + if err != nil { + if errors.Is(err, windows.ERROR_ACCESS_DENIED) { + return nil, fmt.Errorf("windivert: open device (administrator required): %w", err) + } + return nil, fmt.Errorf("windivert: open device: %w", err) + } + } + event, err := windows.CreateEvent(nil, 1, 0, nil) // manual reset, unsignaled + if err != nil { + windows.CloseHandle(device) + return nil, fmt.Errorf("windivert: create event: %w", err) + } + h := &Handle{device: device, event: event} + + err = h.initialize(layer, priority, flags) + if err != nil { + h.Close() + return nil, err + } + err = h.startup(filterBin, filterFlags) + if err != nil { + h.Close() + return nil, err + } + return h, nil +} + +func openDevice() (windows.Handle, error) { + return windows.CreateFile( + driverDevName, + windows.GENERIC_READ|windows.GENERIC_WRITE, + 0, nil, + windows.OPEN_EXISTING, + windows.FILE_ATTRIBUTE_NORMAL|windows.FILE_FLAG_OVERLAPPED, + 0, + ) +} + +func validateOpenArgs(layer Layer, priority int16, flags Flag) error { + if layer != LayerNetwork { + return fmt.Errorf("windivert: invalid layer %d", uint32(layer)) + } + if priority < PriorityLowest || priority > PriorityHighest { + return errors.New("windivert: priority out of range") + } + const supportedFlags = FlagSniff | FlagSendOnly + if flags&^supportedFlags != 0 { + return errors.New("windivert: unknown flag bits") + } + if flags&FlagSniff != 0 && flags&FlagSendOnly != 0 { + return errors.New("windivert: FlagSniff and FlagSendOnly are mutually exclusive") + } + return nil +} + +func (h *Handle) initialize(layer Layer, priority int16, flags Flag) error { + in := buildIoctlInitialize(layer, priority, flags) + // WINDIVERT_VERSION is a 64-byte packed struct; only the first 20 + // bytes (magic, major, minor, bits) carry data, the rest is reserved. + var outBuf [versionStructSize]byte + binary.LittleEndian.PutUint64(outBuf[0:8], magicDLL) + binary.LittleEndian.PutUint32(outBuf[8:12], versionMajor) + binary.LittleEndian.PutUint32(outBuf[12:16], versionMinor) + binary.LittleEndian.PutUint32(outBuf[16:20], uint32(unsafe.Sizeof(uintptr(0))*8)) + _, err := doIoctl(h.device, ioctlInitialize, in[:], outBuf[:], h.event) + if err != nil { + return fmt.Errorf("windivert: initialize ioctl: %w", err) + } + gotMagic := binary.LittleEndian.Uint64(outBuf[0:8]) + if gotMagic != magicSYS { + return fmt.Errorf("windivert: driver magic mismatch (got %d)", gotMagic) + } + gotMajor := binary.LittleEndian.Uint32(outBuf[8:12]) + if gotMajor < versionMajor { + gotMinor := binary.LittleEndian.Uint32(outBuf[12:16]) + return fmt.Errorf("windivert: driver version too old: %d.%d", gotMajor, gotMinor) + } + return nil +} + +func (h *Handle) startup(filterBin []byte, filterFlags uint64) error { + in := buildIoctlStartup(filterFlags) + _, err := doIoctl(h.device, ioctlStartup, in[:], filterBin, h.event) + if err != nil { + return fmt.Errorf("windivert: startup ioctl: %w", err) + } + return nil +} + +// If the handle is closed mid-Recv the error wraps ERROR_OPERATION_ABORTED. +func (h *Handle) Recv(buf []byte) (int, Address, error) { + if len(buf) == 0 { + return 0, Address{}, errors.New("windivert: recv: zero-length buffer") + } + h.addr = Address{} + in := buildIoctlRecv(&h.addr) + n, err := doIoctl(h.device, ioctlRecv, in[:], buf, h.event) + runtime.KeepAlive(h) + if err != nil { + return 0, Address{}, err + } + return int(n), h.addr, nil +} + +// The address's Outbound flag controls whether the packet is sent toward +// the wire (outbound=true) or delivered up the stack (outbound=false). +// IfIdx and SubIfIdx can stay zero — the driver uses the routing table +// when IfIdx=0. +func (h *Handle) Send(packet []byte, addr *Address) (int, error) { + if len(packet) == 0 { + return 0, errors.New("windivert: send: empty packet") + } + if addr == nil { + return 0, errors.New("windivert: send: nil address") + } + h.addr = *addr + in := buildIoctlSend(&h.addr) + n, err := doIoctl(h.device, ioctlSend, in[:], packet, h.event) + runtime.KeepAlive(h) + if err != nil { + return 0, err + } + return int(n), nil +} + +// Idempotent. Aborts any in-flight I/O on the handle. +func (h *Handle) Close() error { + h.closing.Do(func() { + var errs []error + if h.device != 0 { + err := windows.CloseHandle(h.device) + if err != nil { + errs = append(errs, err) + } + h.device = 0 + } + if h.event != 0 { + err := windows.CloseHandle(h.event) + if err != nil { + errs = append(errs, err) + } + h.event = 0 + } + h.closeErr = errors.Join(errs...) + }) + return h.closeErr +} + +// IOCTL codes from windivert_device.h. CTL_CODE macro layout: +// +// (DeviceType << 16) | (Access << 14) | (Function << 2) | Method +const ( + fileDeviceNetwork uint32 = 0x12 + accessReadWrite uint32 = 3 // FILE_READ_DATA | FILE_WRITE_DATA + accessRead uint32 = 1 + + methodInDirect uint32 = 1 + methodOutDirect uint32 = 2 +) + +func ctlCode(deviceType, access, function, method uint32) uint32 { + return (deviceType << 16) | (access << 14) | (function << 2) | method +} + +var ( + ioctlInitialize = ctlCode(fileDeviceNetwork, accessReadWrite, 0x921, methodOutDirect) + ioctlStartup = ctlCode(fileDeviceNetwork, accessReadWrite, 0x922, methodInDirect) + ioctlRecv = ctlCode(fileDeviceNetwork, accessRead, 0x923, methodOutDirect) + ioctlSend = ctlCode(fileDeviceNetwork, accessReadWrite, 0x924, methodInDirect) +) + +// Magic numbers exchanged during INITIALIZE. DLL sends magicDLL in the +// version struct; driver returns magicSYS on success. +const ( + magicDLL uint64 = 0x4C4C447669645724 // "$WdivDLL" in LE bytes + magicSYS uint64 = 0x5359537669645723 // "#WdivSYS" in LE bytes +) + +const ( + versionMajor uint32 = 2 + versionMinor uint32 = 2 +) + +// Size of the WINDIVERT_IOCTL union on wire (packed). +const ioctlSize = 16 + +// Size of WINDIVERT_VERSION on wire (packed). Only the first 20 bytes +// carry data; the rest is reserved zero padding. +const versionStructSize = 64 + +// doIoctl performs a single synchronous (blocking) overlapped +// DeviceIoControl. The handle is opened with FILE_FLAG_OVERLAPPED so +// DeviceIoControl returns ERROR_IO_PENDING; we then wait for completion +// via GetOverlappedResult. Event is passed in so callers can reuse it +// across calls on the same handle (avoids per-call CreateEvent). +func doIoctl(handle windows.Handle, code uint32, in []byte, out []byte, event windows.Handle) (uint32, error) { + var overlapped windows.Overlapped + overlapped.HEvent = event + _ = windows.ResetEvent(event) + + var inPtr *byte + var inLen uint32 + if len(in) > 0 { + inPtr = &in[0] + inLen = uint32(len(in)) + } + var outPtr *byte + var outLen uint32 + if len(out) > 0 { + outPtr = &out[0] + outLen = uint32(len(out)) + } + var returned uint32 + err := windows.DeviceIoControl(handle, code, inPtr, inLen, outPtr, outLen, &returned, &overlapped) + if err != nil && !errors.Is(err, windows.ERROR_IO_PENDING) { + return 0, err + } + err = windows.GetOverlappedResult(handle, &overlapped, &returned, true) + if err != nil { + return 0, err + } + return returned, nil +} + +func buildIoctlInitialize(layer Layer, priority int16, flags Flag) [ioctlSize]byte { + var buf [ioctlSize]byte + binary.LittleEndian.PutUint32(buf[0:4], uint32(layer)) + // The driver expects priority + WINDIVERT_PRIORITY_HIGHEST (30000) so + // the low range maps to non-negative integers. + binary.LittleEndian.PutUint32(buf[4:8], uint32(int32(priority)+int32(PriorityHighest))) + binary.LittleEndian.PutUint64(buf[8:16], uint64(flags)) + return buf +} + +func buildIoctlStartup(filterFlags uint64) [ioctlSize]byte { + var buf [ioctlSize]byte + binary.LittleEndian.PutUint64(buf[0:8], filterFlags) + return buf +} + +// buildIoctlRecv packs a user-space pointer to a WINDIVERT_ADDRESS into +// the ioctl struct. The driver dereferences it to write the address for +// the received packet. Caller must keep the Address alive via +// runtime.KeepAlive. +func buildIoctlRecv(addr *Address) [ioctlSize]byte { + var buf [ioctlSize]byte + binary.LittleEndian.PutUint64(buf[0:8], uint64(uintptr(unsafe.Pointer(addr)))) + binary.LittleEndian.PutUint64(buf[8:16], 0) + return buf +} + +func buildIoctlSend(addr *Address) [ioctlSize]byte { + var buf [ioctlSize]byte + binary.LittleEndian.PutUint64(buf[0:8], uint64(uintptr(unsafe.Pointer(addr)))) + binary.LittleEndian.PutUint64(buf[8:16], uint64(unsafe.Sizeof(Address{}))) + return buf +} diff --git a/transport/internet/finalmask/rawpacket/windivert/windivert.go b/transport/internet/finalmask/rawpacket/windivert/windivert.go new file mode 100644 index 000000000000..9d309886cbe3 --- /dev/null +++ b/transport/internet/finalmask/rawpacket/windivert/windivert.go @@ -0,0 +1,78 @@ +// Package windivert provides a pure-Go binding to the WinDivert kernel +// driver on Windows (amd64 and 386). User-mode WinDivert calls are +// reimplemented in Go; only the signed kernel driver is embedded as an +// asset, since SCM-installed drivers must live on disk and their +// Authenticode signature forbids modification. +// +// Administrator is required for the first Open in a process so SCM can +// load the driver. Upstream: https://github.com/basil00/WinDivert v2.2.2, +// redistributed under its LGPL v3 option; see assets/LICENSE.txt. +package windivert + +import "unsafe" + +const AssetVersion = "2.2.2" + +// MTUMax is WINDIVERT_MTU_MAX from windivert.h (40 + 0xFFFF). Suitable as +// a single-packet receive buffer size. +const MTUMax = 40 + 0xFFFF + +type Layer uint32 + +const LayerNetwork Layer = 0 + +type Flag uint64 + +const ( + // FlagSniff opens a passive observer: the driver copies matching packets + // to userspace without removing them from the network stack. Send is not + // required (and not allowed) on a sniffing handle. + FlagSniff Flag = 0x0001 + // FlagSendOnly opens a write-only injection handle; Recv is not allowed. + FlagSendOnly Flag = 0x0008 +) + +const ( + PriorityHighest int16 = 30000 + PriorityLowest int16 = -30000 +) + +// Address mirrors WINDIVERT_ADDRESS from windivert.h (80 bytes, +// little-endian on both amd64 and 386): +// +// 0: INT64 Timestamp +// 8: UINT32 bitfield: Layer:8 | Event:8 | flags | Reserved1:8 +// 12: UINT32 Reserved2 +// 16: 64 bytes union (WINDIVERT_DATA_NETWORK / FLOW / SOCKET / REFLECT) +type Address struct { + Timestamp int64 + bits uint32 + Reserved2 uint32 + union [64]byte +} + +var _ [80]byte = [unsafe.Sizeof(Address{})]byte{} + +// Bit positions inside the Address's packed flags word. +const ( + addrBitIPv6 = 20 + addrBitIPChecksum = 21 + addrBitTCPChecksum = 22 +) + +func getFlagBit(bits uint32, pos uint) bool { return bits&(1< tcpTimestampBackdate { + spoofedTimestamp -= tcpTimestampBackdate + } else { + spoofedTimestamp = 0 + } + if rewriteTCPOptionTimestamp(tcpOptions, spoofedTimestamp) { + return tcpOptions + } + options := make([]byte, TCPOptionTSLength+2) + EncodeTSOption(spoofedTimestamp, 0, options) + return options +} + +// rewriteTCPOptionTimestamp finds the TS option in tcpOptions and writes +// timestamp into its TSVal field in place. The caller must own tcpOptions +// (parseTCPPacket already returns a private copy on Windows). +func rewriteTCPOptionTimestamp(tcpOptions []byte, timestamp uint32) bool { + for i := 0; i < len(tcpOptions); { + switch tcpOptions[i] { + case TCPOptionEOL: + return false + case TCPOptionNOP: + i++ + continue + } + if i+1 >= len(tcpOptions) { + return false + } + optionLen := int(tcpOptions[i+1]) + if optionLen < 2 || i+optionLen > len(tcpOptions) { + return false + } + if tcpOptions[i] == TCPOptionTS && optionLen == TCPOptionTSLength { + binary.BigEndian.PutUint32(tcpOptions[i+2:], timestamp) + return true + } + i += optionLen + } + return false +} + +func applyTCPChecksum(tcp TCP, srcAddr, dstAddr netip.Addr, payload []byte, corrupt bool) { + tcpLen := int(tcp.DataOffset()) + len(payload) + pseudo := PseudoHeaderChecksum(TCPProtocolNumber, srcAddr.AsSlice(), dstAddr.AsSlice(), uint16(tcpLen)) + payloadChecksum := Checksum(payload, 0) + tcpChecksum := ^tcp.CalculateChecksum(CombineChecksum(pseudo, payloadChecksum)) + if corrupt { + tcpChecksum ^= 0xFFFF + } + tcp.SetChecksum(tcpChecksum) +} diff --git a/transport/internet/tls/tlsspoof/raw_darwin.go b/transport/internet/tls/tlsspoof/raw_darwin.go new file mode 100644 index 000000000000..3b45d17023be --- /dev/null +++ b/transport/internet/tls/tlsspoof/raw_darwin.go @@ -0,0 +1,198 @@ +package tlsspoof + +import ( + "encoding/binary" + "net" + "net/netip" + "strconv" + "strings" + "sync" + "syscall" + + "errors" + "fmt" + + "golang.org/x/sys/unix" +) + +const PlatformSupported = true + +// Offsets into xinpcb_n within each net.inet.tcp.pcblist_n record, identical +// to the values used by common/process/searcher_darwin_shared.go. +const ( + darwinXinpgenSize = 24 + darwinXsocketOffset = 104 + darwinXinpcbForeignPort = 16 + darwinXinpcbLocalPort = 18 + darwinXinpcbVFlag = 44 + darwinXinpcbForeignAddr = 48 + darwinXinpcbLocalAddr = 64 + darwinXinpcbIPv4Offset = 12 + + darwinTCPExtraSize = 208 + + darwinXtcpcbSndNxtOffset = 56 + darwinXtcpcbRcvNxtOffset = 80 +) + +// darwinStructSize returns the size of xinpcb_n for the running Darwin kernel. +// Darwin 22 (macOS 13 Ventura) grew the struct from 384 to 408 bytes; there is +// no ABI-stable way to read it, so we key off the kernel version. +var darwinStructSize = sync.OnceValues(func() (int, error) { + value, err := syscall.Sysctl("kern.osrelease") + if err != nil { + return 0, func(err error, m string) error { return err }(err, "sysctl kern.osrelease") + } + major, _, ok := strings.Cut(value, ".") + if !ok { + return 0, fmt.Errorf("unexpected kern.osrelease format: %s", value) + } + n, err := strconv.ParseInt(major, 10, 64) + if err != nil { + return 0, func(err error, m string) error { return err }(err, "parse kern.osrelease major version: ") + } + if n >= 22 { + return 408, nil + } + return 384, nil +}) + +type darwinSpoofer struct { + method Method + src netip.AddrPort + dst netip.AddrPort + rawFD int + rawSockAddr unix.Sockaddr + sendNext uint32 + receiveNext uint32 +} + +func newRawSpoofer(conn net.Conn, method Method) (rawSpoofer, error) { + if method == MethodWrongTimestamp { + return nil, errors.New("tls_spoof: wrong-timestamp is not supported on macOS") + } + _, src, dst, err := tcpEndpoints(conn) + if err != nil { + return nil, err + } + fd, sockaddr, err := openDarwinRawSocket(src, dst) + if err != nil { + return nil, err + } + sendNext, receiveNext, err := readDarwinTCPSequence(src, dst) + if err != nil { + unix.Close(fd) + return nil, err + } + return &darwinSpoofer{ + method: method, + src: src, + dst: dst, + rawFD: fd, + rawSockAddr: sockaddr, + sendNext: sendNext, + receiveNext: receiveNext, + }, nil +} + +// readDarwinTCPSequence scans net.inet.tcp.pcblist_n for the PCB that matches +// src -> dst and returns (snd_nxt, rcv_nxt). These live in xtcpcb_n at the end +// of each record; see darwin-xnu bsd/netinet/in_pcblist.c:get_pcblist_n. +func readDarwinTCPSequence(src, dst netip.AddrPort) (uint32, uint32, error) { + buffer, err := unix.SysctlRaw("net.inet.tcp.pcblist_n") + if err != nil { + return 0, 0, func(err error, m string) error { return err }(err, "sysctl net.inet.tcp.pcblist_n") + } + structSize, err := darwinStructSize() + if err != nil { + return 0, 0, err + } + itemSize := structSize + darwinTCPExtraSize + for i := darwinXinpgenSize; i+itemSize <= len(buffer); i += itemSize { + inpcb := buffer[i : i+darwinXsocketOffset] + xtcpcb := buffer[i+structSize : i+itemSize] + localPort := binary.BigEndian.Uint16(inpcb[darwinXinpcbLocalPort : darwinXinpcbLocalPort+2]) + remotePort := binary.BigEndian.Uint16(inpcb[darwinXinpcbForeignPort : darwinXinpcbForeignPort+2]) + if localPort != src.Port() || remotePort != dst.Port() { + continue + } + versionFlag := inpcb[darwinXinpcbVFlag] + var localAddr, remoteAddr netip.Addr + switch { + case versionFlag&0x1 != 0: + localAddr = netip.AddrFrom4([4]byte(inpcb[darwinXinpcbLocalAddr+darwinXinpcbIPv4Offset : darwinXinpcbLocalAddr+darwinXinpcbIPv4Offset+4])) + remoteAddr = netip.AddrFrom4([4]byte(inpcb[darwinXinpcbForeignAddr+darwinXinpcbIPv4Offset : darwinXinpcbForeignAddr+darwinXinpcbIPv4Offset+4])) + case versionFlag&0x2 != 0: + localAddr = netip.AddrFrom16([16]byte(inpcb[darwinXinpcbLocalAddr : darwinXinpcbLocalAddr+16])) + remoteAddr = netip.AddrFrom16([16]byte(inpcb[darwinXinpcbForeignAddr : darwinXinpcbForeignAddr+16])) + default: + continue + } + if localAddr.Unmap() != src.Addr() || remoteAddr.Unmap() != dst.Addr() { + continue + } + sendNext := binary.NativeEndian.Uint32(xtcpcb[darwinXtcpcbSndNxtOffset : darwinXtcpcbSndNxtOffset+4]) + receiveNext := binary.NativeEndian.Uint32(xtcpcb[darwinXtcpcbRcvNxtOffset : darwinXtcpcbRcvNxtOffset+4]) + return sendNext, receiveNext, nil + } + return 0, 0, fmt.Errorf("tls_spoof: connection %v->%v not found in pcblist_n", src, dst) +} + +func openDarwinRawSocket(src, dst netip.AddrPort) (int, unix.Sockaddr, error) { + if dst.Addr().Is4() { + return openIPv4RawSocket(dst) + } + // macOS does not accept IPV6_HDRINCL on AF_INET6 SOCK_RAW IPPROTO_TCP + // sockets, so the kernel builds the IPv6 header itself. Bind to the real + // connection's source address so in6_selectsrc returns it, and rely on + // in6p_cksum defaulting to -1 so the user-supplied TCP checksum is + // preserved (including deliberately corrupted ones). + fd, err := unix.Socket(unix.AF_INET6, unix.SOCK_RAW, unix.IPPROTO_TCP) + if err != nil { + return -1, nil, func(err error, m string) error { return err }(err, "open AF_INET6 SOCK_RAW") + } + err = unix.Bind(fd, &unix.SockaddrInet6{Addr: src.Addr().As16()}) + if err != nil { + unix.Close(fd) + return -1, nil, func(err error, m string) error { return err }(err, "bind AF_INET6 SOCK_RAW") + } + sockaddr := &unix.SockaddrInet6{Port: int(dst.Port()), Addr: dst.Addr().As16()} + return fd, sockaddr, nil +} + +func (s *darwinSpoofer) Inject(payload []byte) error { + if !s.src.Addr().Is4() { + segment, err := buildSpoofTCPSegment(s.method, s.src, s.dst, s.sendNext, s.receiveNext, 0, payload) + if err != nil { + return err + } + err = unix.Sendto(s.rawFD, segment, 0, s.rawSockAddr) + if err != nil { + return func(err error, m string) error { return err }(err, "sendto raw socket") + } + return nil + } + frame, err := buildSpoofFrame(s.method, s.src, s.dst, s.sendNext, s.receiveNext, 0, nil, payload) + if err != nil { + return err + } + // Darwin inherits the historical BSD quirk: with IP_HDRINCL the kernel + // expects ip_len and ip_off in host byte order, not network byte order. + ip := IPv4(frame) + binary.NativeEndian.PutUint16(ip[2:4], ip.TotalLength()) + binary.NativeEndian.PutUint16(ip[6:8], uint16(ip.Flags())<<13|ip.FragmentOffset()) + err = unix.Sendto(s.rawFD, frame, 0, s.rawSockAddr) + if err != nil { + return func(err error, m string) error { return err }(err, "sendto raw socket") + } + return nil +} + +func (s *darwinSpoofer) Close() error { + if s.rawFD < 0 { + return nil + } + err := unix.Close(s.rawFD) + s.rawFD = -1 + return err +} diff --git a/transport/internet/tls/tlsspoof/raw_freebsd.go b/transport/internet/tls/tlsspoof/raw_freebsd.go new file mode 100644 index 000000000000..0f39a0ee5c39 --- /dev/null +++ b/transport/internet/tls/tlsspoof/raw_freebsd.go @@ -0,0 +1,172 @@ +package tlsspoof + +import ( + "encoding/binary" + "errors" + "fmt" + "net" + "net/netip" + "syscall" + "unsafe" + + "golang.org/x/sys/unix" +) + +const PlatformSupported = true + +// FreeBSD tcp_info offsets for snd_nxt and rcv_nxt. +// Derived from FreeBSD sys/netinet/tcp.h struct tcp_info layout. +// +// struct tcp_info { +// u8 state, __ca, __retrans, __probes, __backoff, opts, wscale = 8 bytes (with pad) +// u32 rto, __ato, snd_mss, rcv_mss = 16 bytes (offset 8) +// u32 __unacked, __sacked, __lost, __retrans, __fackets = 20 bytes (offset 24) +// u32 __last_data_sent, __last_ack_sent, last_data_recv, __last_ack_recv = 16 bytes (offset 44) +// u32 __pmtu, __rcv_ssthresh, rtt, rttvar, snd_ssthresh, snd_cwnd, __advmss, __reordering = 32 bytes (offset 60) +// u32 __rcv_rtt, rcv_space = 8 bytes (offset 92) +// u32 snd_wnd, snd_bwnd = 8 bytes (offset 100) +// u32 snd_nxt, rcv_nxt = 8 bytes (offset 108) +// ... remaining fields +// } +const ( + freebsdTCPInfoSndNxtOffset = 108 + freebsdTCPInfoRcvNxtOffset = 112 + freebsdTCPInfoMinSize = 116 // must read at least through rcv_nxt +) + +type freebsdSpoofer struct { + method Method + src netip.AddrPort + dst netip.AddrPort + rawFD int + rawSockAddr unix.Sockaddr + sendNext uint32 + receiveNext uint32 +} + +func newRawSpoofer(conn net.Conn, method Method) (rawSpoofer, error) { + if method == MethodWrongTimestamp { + return nil, errors.New("tls_spoof: wrong-timestamp is not supported on FreeBSD") + } + tcpConn, src, dst, err := tcpEndpoints(conn) + if err != nil { + return nil, err + } + fd, sockaddr, err := openFreeBSDRawSocket(src, dst) + if err != nil { + return nil, err + } + sendNext, receiveNext, err := readFreeBSDTCPSequence(tcpConn) + if err != nil { + unix.Close(fd) + return nil, err + } + return &freebsdSpoofer{ + method: method, + src: src, + dst: dst, + rawFD: fd, + rawSockAddr: sockaddr, + sendNext: sendNext, + receiveNext: receiveNext, + }, nil +} + +// readFreeBSDTCPSequence retrieves snd_nxt and rcv_nxt via TCP_INFO getsockopt. +func readFreeBSDTCPSequence(conn *net.TCPConn) (uint32, uint32, error) { + raw, err := conn.SyscallConn() + if err != nil { + return 0, 0, fmt.Errorf("tls_spoof: SyscallConn: %w", err) + } + var sendNext, receiveNext uint32 + var sockErr error + err = raw.Control(func(fd uintptr) { + buf := make([]byte, 256) // generous buffer for tcp_info + bufLen := uint32(len(buf)) + _, _, errno := syscall.Syscall6( + syscall.SYS_GETSOCKOPT, + fd, + uintptr(syscall.IPPROTO_TCP), + uintptr(0x20), // TCP_INFO = 0x20 + uintptr(unsafe.Pointer(&buf[0])), + uintptr(unsafe.Pointer(&bufLen)), + 0, + ) + if errno != 0 { + sockErr = fmt.Errorf("tls_spoof: getsockopt TCP_INFO: %w", errno) + return + } + if bufLen < freebsdTCPInfoMinSize { + sockErr = fmt.Errorf("tls_spoof: TCP_INFO too short: %d < %d", bufLen, freebsdTCPInfoMinSize) + return + } + sendNext = binary.NativeEndian.Uint32(buf[freebsdTCPInfoSndNxtOffset : freebsdTCPInfoSndNxtOffset+4]) + receiveNext = binary.NativeEndian.Uint32(buf[freebsdTCPInfoRcvNxtOffset : freebsdTCPInfoRcvNxtOffset+4]) + }) + if err != nil { + return 0, 0, err + } + if sockErr != nil { + return 0, 0, sockErr + } + return sendNext, receiveNext, nil +} + +func openFreeBSDRawSocket(src, dst netip.AddrPort) (int, unix.Sockaddr, error) { + if dst.Addr().Is4() { + return openIPv4RawSocket(dst) + } + // FreeBSD, like macOS, does not support IPV6_HDRINCL on SOCK_RAW/IPPROTO_TCP. + // The kernel constructs the IPv6 header. Bind to the source address + // and let the kernel fill in the IPv6 header automatically. + fd, err := unix.Socket(unix.AF_INET6, unix.SOCK_RAW, unix.IPPROTO_TCP) + if err != nil { + return -1, nil, fmt.Errorf("tls_spoof: open AF_INET6 SOCK_RAW: %w", err) + } + err = unix.Bind(fd, &unix.SockaddrInet6{Addr: src.Addr().As16()}) + if err != nil { + unix.Close(fd) + return -1, nil, fmt.Errorf("tls_spoof: bind AF_INET6 SOCK_RAW: %w", err) + } + sockaddr := &unix.SockaddrInet6{Port: int(dst.Port()), Addr: dst.Addr().As16()} + return fd, sockaddr, nil +} + +func (s *freebsdSpoofer) Inject(payload []byte) error { + if !s.src.Addr().Is4() { + // IPv6: kernel builds the IP header, we supply TCP segment only. + segment, err := buildSpoofTCPSegment(s.method, s.src, s.dst, s.sendNext, s.receiveNext, 0, payload) + if err != nil { + return err + } + err = unix.Sendto(s.rawFD, segment, 0, s.rawSockAddr) + if err != nil { + return fmt.Errorf("tls_spoof: sendto raw socket: %w", err) + } + return nil + } + // IPv4: we build the full IP+TCP frame with IP_HDRINCL. + frame, err := buildSpoofFrame(s.method, s.src, s.dst, s.sendNext, s.receiveNext, 0, nil, payload) + if err != nil { + return err + } + // FreeBSD inherits the historical BSD quirk: with IP_HDRINCL the kernel + // expects ip_len and ip_off in host byte order, not network byte order. + ip := IPv4(frame) + binary.NativeEndian.PutUint16(ip[2:4], ip.TotalLength()) + binary.NativeEndian.PutUint16(ip[6:8], uint16(ip.Flags())<<13|ip.FragmentOffset()) + err = unix.Sendto(s.rawFD, frame, 0, s.rawSockAddr) + if err != nil { + return fmt.Errorf("tls_spoof: sendto raw socket: %w", err) + } + return nil +} + +func (s *freebsdSpoofer) Close() error { + if s.rawFD < 0 { + return nil + } + err := unix.Close(s.rawFD) + s.rawFD = -1 + return err +} diff --git a/transport/internet/tls/tlsspoof/raw_linux.go b/transport/internet/tls/tlsspoof/raw_linux.go new file mode 100644 index 000000000000..dc5c7311869c --- /dev/null +++ b/transport/internet/tls/tlsspoof/raw_linux.go @@ -0,0 +1,166 @@ +package tlsspoof + +import ( + "fmt" + "net" + "net/netip" + + "golang.org/x/sys/unix" +) + +const PlatformSupported = true + +const ( + // Values of enum { TCP_NO_QUEUE, TCP_RECV_QUEUE, TCP_SEND_QUEUE } from + // include/net/tcp.h; not exported by golang.org/x/sys/unix. + tcpRecvQueue = 1 + tcpSendQueue = 2 +) + +type linuxSpoofer struct { + method Method + src netip.AddrPort + dst netip.AddrPort + rawFD int + rawSockAddr unix.Sockaddr + sendNext uint32 + receiveNext uint32 + timestamp uint32 +} + +func newRawSpoofer(conn net.Conn, method Method) (rawSpoofer, error) { + tcpConn, src, dst, err := tcpEndpoints(conn) + if err != nil { + return nil, err + } + fd, sockaddr, err := openLinuxRawSocket(dst) + if err != nil { + return nil, err + } + spoofer := &linuxSpoofer{ + method: method, + src: src, + dst: dst, + rawFD: fd, + rawSockAddr: sockaddr, + } + err = spoofer.loadSequenceNumbers(tcpConn) + if err != nil { + unix.Close(fd) + return nil, err + } + return spoofer, nil +} + +func openLinuxRawSocket(dst netip.AddrPort) (int, unix.Sockaddr, error) { + if dst.Addr().Is4() { + return openIPv4RawSocket(dst) + } + fd, err := unix.Socket(unix.AF_INET6, unix.SOCK_RAW, unix.IPPROTO_TCP) + if err != nil { + return -1, nil, func(err error, m string) error { return err }(err, "open AF_INET6 SOCK_RAW") + } + err = unix.SetsockoptInt(fd, unix.IPPROTO_IPV6, unix.IPV6_HDRINCL, 1) + if err != nil { + unix.Close(fd) + return -1, nil, func(err error, m string) error { return err }(err, "set IPV6_HDRINCL") + } + // Linux raw IPv6 sockets interpret sin6_port as a nexthdr protocol number + // (see raw(7)); any value other than 0 or the socket's IPPROTO_TCP causes + // sendto to fail with EINVAL. The destination is already encoded in the + // user-supplied IPv6 header under IPV6_HDRINCL. + sockaddr := &unix.SockaddrInet6{Addr: dst.Addr().As16()} + return fd, sockaddr, nil +} + +// loadSequenceNumbers puts the socket briefly into TCP_REPAIR mode to read +// snd_nxt and rcv_nxt from the kernel. TCP_REPAIR requires CAP_NET_ADMIN; +// callers must run as root or grant both CAP_NET_RAW and CAP_NET_ADMIN. +// +// If the TCP_REPAIR_OFF revert fails, the socket would stay in TCP_REPAIR +// state and subsequent Write() calls would silently buffer instead of sending. +// Surface that error so callers can abort. +func (s *linuxSpoofer) loadSequenceNumbers(tcpConn *net.TCPConn) error { + rawConn, err := tcpConn.SyscallConn() + if err != nil { + return err + } + var ctrlErr error + err = rawConn.Control(func(raw uintptr) { + fd := int(raw) + + if s.method == MethodWrongTimestamp { + timestamp, tsErr := unix.GetsockoptInt(fd, unix.IPPROTO_TCP, unix.TCP_TIMESTAMP) + if tsErr != nil { + ctrlErr = fmt.Errorf("tls_spoof: read timestamp: %w", tsErr) + return + } + s.timestamp = uint32(timestamp) + } + + ctrlErr = unix.SetsockoptInt(fd, unix.IPPROTO_TCP, unix.TCP_REPAIR, unix.TCP_REPAIR_ON) + if ctrlErr != nil { + ctrlErr = fmt.Errorf("tls_spoof: enter TCP_REPAIR (need CAP_NET_ADMIN): %w", ctrlErr) + return + } + defer func() { + offErr := unix.SetsockoptInt(fd, unix.IPPROTO_TCP, unix.TCP_REPAIR, unix.TCP_REPAIR_OFF) + if offErr != nil { + offErr = fmt.Errorf("tls_spoof: leave TCP_REPAIR: %w", offErr) + if ctrlErr == nil { + ctrlErr = offErr + } else { + ctrlErr = fmt.Errorf("%v; also %w", ctrlErr, offErr) + } + } + }() + + ctrlErr = unix.SetsockoptInt(fd, unix.IPPROTO_TCP, unix.TCP_REPAIR_QUEUE, tcpSendQueue) + if ctrlErr != nil { + ctrlErr = fmt.Errorf("tls_spoof: select TCP_SEND_QUEUE: %w", ctrlErr) + return + } + sendSequence, seqErr := unix.GetsockoptInt(fd, unix.IPPROTO_TCP, unix.TCP_QUEUE_SEQ) + if seqErr != nil { + ctrlErr = fmt.Errorf("tls_spoof: read send queue sequence: %w", seqErr) + return + } + ctrlErr = unix.SetsockoptInt(fd, unix.IPPROTO_TCP, unix.TCP_REPAIR_QUEUE, tcpRecvQueue) + if ctrlErr != nil { + ctrlErr = fmt.Errorf("tls_spoof: select TCP_RECV_QUEUE: %w", ctrlErr) + return + } + receiveSequence, seqErr := unix.GetsockoptInt(fd, unix.IPPROTO_TCP, unix.TCP_QUEUE_SEQ) + if seqErr != nil { + ctrlErr = fmt.Errorf("tls_spoof: read recv queue sequence: %w", seqErr) + return + } + s.sendNext = uint32(sendSequence) + s.receiveNext = uint32(receiveSequence) + }) + if err != nil { + return err + } + return ctrlErr +} + +func (s *linuxSpoofer) Inject(payload []byte) error { + frame, err := buildSpoofFrame(s.method, s.src, s.dst, s.sendNext, s.receiveNext, s.timestamp, nil, payload) + if err != nil { + return err + } + err = unix.Sendto(s.rawFD, frame, 0, s.rawSockAddr) + if err != nil { + return func(err error, m string) error { return err }(err, "sendto raw socket") + } + return nil +} + +func (s *linuxSpoofer) Close() error { + if s.rawFD < 0 { + return nil + } + err := unix.Close(s.rawFD) + s.rawFD = -1 + return err +} diff --git a/transport/internet/tls/tlsspoof/raw_stub.go b/transport/internet/tls/tlsspoof/raw_stub.go new file mode 100644 index 000000000000..78be3c23391d --- /dev/null +++ b/transport/internet/tls/tlsspoof/raw_stub.go @@ -0,0 +1,15 @@ +//go:build !linux && !darwin && !freebsd && !(windows && (amd64 || 386)) + +package tlsspoof + +import ( + "net" + + "errors" +) + +const PlatformSupported = false + +func newRawSpoofer(conn net.Conn, method Method) (rawSpoofer, error) { + return nil, errors.New("tls_spoof: unsupported platform") +} diff --git a/transport/internet/tls/tlsspoof/raw_unix.go b/transport/internet/tls/tlsspoof/raw_unix.go new file mode 100644 index 000000000000..7d5c32e3b5ef --- /dev/null +++ b/transport/internet/tls/tlsspoof/raw_unix.go @@ -0,0 +1,24 @@ +//go:build linux || darwin || freebsd + +package tlsspoof + +import ( + "net/netip" + + "golang.org/x/sys/unix" +) + +func openIPv4RawSocket(dst netip.AddrPort) (int, unix.Sockaddr, error) { + fd, err := unix.Socket(unix.AF_INET, unix.SOCK_RAW, unix.IPPROTO_TCP) + if err != nil { + return -1, nil, func(err error, m string) error { return err }(err, "open AF_INET SOCK_RAW") + } + err = unix.SetsockoptInt(fd, unix.IPPROTO_IP, unix.IP_HDRINCL, 1) + if err != nil { + unix.Close(fd) + return -1, nil, func(err error, m string) error { return err }(err, "set IP_HDRINCL") + } + sockaddr := &unix.SockaddrInet4{Port: int(dst.Port())} + sockaddr.Addr = dst.Addr().As4() + return fd, sockaddr, nil +} diff --git a/transport/internet/tls/tlsspoof/raw_windows.go b/transport/internet/tls/tlsspoof/raw_windows.go new file mode 100644 index 000000000000..17878ffce3dd --- /dev/null +++ b/transport/internet/tls/tlsspoof/raw_windows.go @@ -0,0 +1,234 @@ +//go:build windows && (amd64 || 386) + +package tlsspoof + +import ( + "errors" + "net" + "net/netip" + "slices" + "sync" + "sync/atomic" + "time" + + "github.com/xtls/xray-core/transport/internet/tls/tlsspoof/windivert" + "golang.org/x/sys/windows" +) + +const PlatformSupported = true + +// closeGracePeriod caps how long Close() waits for the divert goroutine to +// observe the kernel-emitted real ClientHello and perform the reorder +// (fake → real). In practice this completes in microseconds; the cap +// bounds the pathological case where the kernel buffers the packet. +const closeGracePeriod = 2 * time.Second + +// windowsSpoofer uses a single WinDivert handle for both capture and +// injection. Sequential Send() calls on one handle traverse one driver queue, +// so the fake provably precedes the released real on the wire — a guarantee +// two separate handles cannot make because cross-handle order depends on the +// scheduler. +type windowsSpoofer struct { + method Method + src, dst netip.AddrPort + divertH *windivert.Handle + + fakeReady chan []byte // buffered(1): staged by Inject + done chan struct{} // closed by run() on exit + closeOnce sync.Once + runErr atomic.Pointer[error] +} + +func newRawSpoofer(conn net.Conn, method Method) (rawSpoofer, error) { + _, src, dst, err := tcpEndpoints(conn) + if err != nil { + return nil, err + } + filter, err := windivert.OutboundTCP(src, dst) + if err != nil { + return nil, err + } + divertH, err := windivert.Open(filter, windivert.LayerNetwork, 0, 0) + if err != nil { + return nil, err + } + s := &windowsSpoofer{ + method: method, + src: src, + dst: dst, + divertH: divertH, + fakeReady: make(chan []byte, 1), + done: make(chan struct{}), + } + go s.run() + return s, nil +} + +func (s *windowsSpoofer) Inject(payload []byte) error { + select { + case s.fakeReady <- payload: + return nil + case <-s.done: + if p := s.runErr.Load(); p != nil { + return *p + } + return errors.New("tls_spoof: spoofer closed before Inject") + } +} + +func (s *windowsSpoofer) Close() error { + s.closeOnce.Do(func() { + // Give run() a grace window to finish handling the real packet. + select { + case <-s.done: + case <-time.After(closeGracePeriod): + // Force Recv() to return by closing the divert handle. + s.divertH.Close() + <-s.done + } + }) + if p := s.runErr.Load(); p != nil { + return *p + } + return nil +} + +func (s *windowsSpoofer) recordErr(err error) { s.runErr.Store(&err) } + +func (s *windowsSpoofer) run() { + defer close(s.done) + defer s.divertH.Close() + + buf := make([]byte, windivert.MTUMax) + for { + n, addr, err := s.divertH.Recv(buf) + if err != nil { + if errors.Is(err, windows.ERROR_OPERATION_ABORTED) || + errors.Is(err, windows.ERROR_NO_DATA) { + return + } + s.recordErr(err) + return + } + pkt := buf[:n] + seq, ack, tcpOptions, payloadLen, ok := parseTCPPacket(pkt, addr.IPv6()) + if !ok { + // Our filter is OutboundTCP(src, dst); a non-TCP or truncated + // match means driver state is suspect. Re-inject so the kernel + // still sees the byte stream, then abort — continuing would risk + // reordering against an unknown reference point. + _, sendErr := s.divertH.Send(pkt, &addr) + if sendErr != nil { + s.recordErr(sendErr) + return + } + s.recordErr(errors.New("windivert received malformed packet matching spoof filter")) + return + } + if payloadLen == 0 { + // Handshake ACK, keepalive, FIN — pass through unchanged. + _, err := s.divertH.Send(pkt, &addr) + if err != nil { + s.recordErr(err) + return + } + continue + } + + // Non-empty outbound TCP payload = the real ClientHello. + var fake []byte + select { + case fake = <-s.fakeReady: + default: + // Inject() not yet called — pass through and keep observing. + _, err := s.divertH.Send(pkt, &addr) + if err != nil { + s.recordErr(err) + return + } + continue + } + + var timestamp uint32 + if tsVal, hasTS := ParseTCPOptions(tcpOptions); hasTS { + timestamp = tsVal + } + frame, err := buildSpoofFrame(s.method, s.src, s.dst, seq, ack, timestamp, tcpOptions, fake) + if err != nil { + s.recordErr(err) + return + } + fakeAddr := addr // inherit Outbound, IfIdx + // buildSpoofFrame emits ready-to-wire bytes. The driver recomputes + // checksums on Send when TCPChecksum/IPChecksum are 0 — which would + // overwrite the intentionally corrupt checksum in WrongChecksum mode. + // Force both to 1 to keep our bytes intact. + fakeAddr.SetIPChecksum(true) + fakeAddr.SetTCPChecksum(true) + _, err = s.divertH.Send(frame, &fakeAddr) + if err != nil { + s.recordErr(err) + return + } + _, err = s.divertH.Send(pkt, &addr) + if err != nil { + s.recordErr(err) + return + } + return // single-shot reorder complete + } +} + +func parseTCPPacket(pkt []byte, isV6 bool) (seq, ack uint32, options []byte, payloadLen int, ok bool) { + if isV6 { + if len(pkt) < IPv6MinimumSize+TCPMinimumSize { + return 0, 0, nil, 0, false + } + ip := IPv6(pkt) + if ip.TransportProtocol() != TCPProtocolNumber { + return 0, 0, nil, 0, false + } + tcp := TCP(pkt[IPv6MinimumSize:]) + tcpHdr := int(tcp.DataOffset()) + if tcpHdr < TCPMinimumSize || IPv6MinimumSize+tcpHdr > len(pkt) { + return 0, 0, nil, 0, false + } + total := IPv6MinimumSize + int(ip.PayloadLength()) + if total == IPv6MinimumSize || total > len(pkt) { + total = len(pkt) + } + if total < IPv6MinimumSize+tcpHdr { + return 0, 0, nil, 0, false + } + return tcp.SequenceNumber(), tcp.AckNumber(), slices.Clone(tcp.Options()), + total - IPv6MinimumSize - tcpHdr, true + } + if len(pkt) < IPv4MinimumSize+TCPMinimumSize { + return 0, 0, nil, 0, false + } + ip := IPv4(pkt) + if ip.Protocol() != TCPProtocolNumber { + return 0, 0, nil, 0, false + } + ihl := int(ip.HeaderLength()) + // ihl+TCPMinimumSize guards the TCP-header field reads below; without + // this, an IPv4 packet with options (ihl>20) against a 40-byte buffer + // reads past the TCP slice when calling DataOffset. + if ihl < IPv4MinimumSize || ihl+TCPMinimumSize > len(pkt) { + return 0, 0, nil, 0, false + } + tcp := TCP(pkt[ihl:]) + tcpHdr := int(tcp.DataOffset()) + if tcpHdr < TCPMinimumSize || ihl+tcpHdr > len(pkt) { + return 0, 0, nil, 0, false + } + total := int(ip.TotalLength()) + if total == 0 || total > len(pkt) { + total = len(pkt) + } + if total < ihl+tcpHdr { + return 0, 0, nil, 0, false + } + return tcp.SequenceNumber(), tcp.AckNumber(), slices.Clone(tcp.Options()), + total - ihl - tcpHdr, true +} diff --git a/transport/internet/tls/tlsspoof/spoof.go b/transport/internet/tls/tlsspoof/spoof.go new file mode 100644 index 000000000000..6a9eae93a45b --- /dev/null +++ b/transport/internet/tls/tlsspoof/spoof.go @@ -0,0 +1,182 @@ +package tlsspoof + +import ( + "errors" + "fmt" + "net" + "runtime" + "syscall" +) + +type Method int + +const ( + MethodWrongSequence Method = iota + MethodWrongChecksum + MethodWrongAcknowledgment + MethodWrongMD5Sig + MethodWrongTimestamp +) + +const ( + MethodNameWrongSequence = "wrong-sequence" + MethodNameWrongChecksum = "wrong-checksum" + MethodNameWrongAcknowledgment = "wrong-ack" + MethodNameWrongMD5Sig = "wrong-md5" + MethodNameWrongTimestamp = "wrong-timestamp" +) + +func ParseOptions(spoof, method string) (string, Method, error) { + if spoof == "" { + if method != "" { + return "", 0, errors.New("spoof_method requires spoof") + } + return "", 0, nil + } + if net.ParseIP(spoof) != nil { + return "", 0, errors.New("tls_spoof: IP-literal server names are not allowed") + } + if !PlatformSupported { + return "", 0, errors.New("tls_spoof is not supported on this platform") + } + parsedMethod, err := ParseMethod(method) + if err != nil { + return "", 0, err + } + return spoof, parsedMethod, nil +} + +func ParseMethod(s string) (Method, error) { + switch s { + case "", MethodNameWrongSequence: + return MethodWrongSequence, nil + case MethodNameWrongChecksum: + return MethodWrongChecksum, nil + case MethodNameWrongAcknowledgment: + return MethodWrongAcknowledgment, nil + case MethodNameWrongMD5Sig: + return MethodWrongMD5Sig, nil + case MethodNameWrongTimestamp: + return MethodWrongTimestamp, nil + default: + return 0, fmt.Errorf("tls_spoof: unknown method: %s", s) + } +} + +func (m Method) String() string { + switch m { + case MethodWrongSequence: + return MethodNameWrongSequence + case MethodWrongChecksum: + return MethodNameWrongChecksum + case MethodWrongAcknowledgment: + return MethodNameWrongAcknowledgment + case MethodWrongMD5Sig: + return MethodNameWrongMD5Sig + case MethodWrongTimestamp: + return MethodNameWrongTimestamp + default: + return "unknown" + } +} + +type rawSpoofer interface { + Inject(payload []byte) error + Close() error +} + +type Conn struct { + net.Conn + spoofer rawSpoofer + fakeHello []byte + injectionCount int + maxInjections int // how many times to inject; default 1 +} + +// NewConn wraps a connection with TLS spoofing. maxInjections controls how +// many Write() calls will trigger a fake ClientHello injection (0 or 1 = single-shot). +func NewConn(conn net.Conn, method Method, fakeSNI string, maxInjections int) (*Conn, error) { + spoofer, err := newRawSpoofer(conn, method) + if err != nil { + return nil, wrapPermissionError(err) + } + result, err := newConn(conn, spoofer, fakeSNI, maxInjections) + if err != nil { + spoofer.Close() + return nil, err + } + return result, nil +} + +func newConn(conn net.Conn, spoofer rawSpoofer, fakeSNI string, maxInjections int) (*Conn, error) { + fakeHello, err := buildFakeClientHello(fakeSNI) + if err != nil { + return nil, func(err error, m string) error { return err }(err, "tls_spoof: build fake ClientHello") + } + if maxInjections <= 0 { + maxInjections = 1 + } + return &Conn{ + Conn: conn, + spoofer: spoofer, + fakeHello: fakeHello, + maxInjections: maxInjections, + }, nil +} + +func (c *Conn) Write(b []byte) (n int, err error) { + if c.injectionCount >= c.maxInjections { + return c.Conn.Write(b) + } + err = c.spoofer.Inject(c.fakeHello) + if err != nil { + return 0, func(err error, m string) error { return err }(err, "tls_spoof: inject") + } + c.injectionCount++ + if c.injectionCount >= c.maxInjections { + closeErr := c.spoofer.Close() + if closeErr != nil { + return 0, func(err error, m string) error { return err }(closeErr, "tls_spoof: close spoofer") + } + } + return c.Conn.Write(b) +} + +func (c *Conn) Close() error { + return func(e1, e2 error) error { + if e1 != nil { + return e1 + } + return e2 + }(c.Conn.Close(), c.spoofer.Close()) +} + +func (c *Conn) ReaderReplaceable() bool { + return true +} + +func (c *Conn) WriterReplaceable() bool { + return c.injectionCount >= c.maxInjections +} + +func (c *Conn) Upstream() any { + return c.Conn +} + +// wrapPermissionError adds platform-specific hints when the spoofer fails +// due to insufficient privileges. +func wrapPermissionError(err error) error { + if !errors.Is(err, syscall.EPERM) && !errors.Is(err, syscall.EACCES) { + return err + } + switch runtime.GOOS { + case "linux": + return fmt.Errorf("%w\n Hint: run as root, or grant capabilities:\n sudo setcap cap_net_raw,cap_net_admin+ep /path/to/xray", err) + case "darwin": + return fmt.Errorf("%w\n Hint: TLS spoofing requires root on macOS. Run with: sudo ./xray", err) + case "freebsd": + return fmt.Errorf("%w\n Hint: TLS spoofing requires root on FreeBSD. Run with: sudo ./xray", err) + default: + return err + } +} diff --git a/transport/internet/tls/tlsspoof/spoof_freebsd_test.go b/transport/internet/tls/tlsspoof/spoof_freebsd_test.go new file mode 100644 index 000000000000..a8ab2ccae823 --- /dev/null +++ b/transport/internet/tls/tlsspoof/spoof_freebsd_test.go @@ -0,0 +1,82 @@ +package tlsspoof + +import ( + "net" + "net/netip" + "os/user" + "testing" + + "golang.org/x/sys/unix" +) + +func TestFreeBSDTCPSequence(t *testing.T) { + u, err := user.Current() + if err == nil && u.Uid != "0" { + t.Skip("skipping test; must be root to use raw sockets / TCP_INFO on FreeBSD") + } + + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatalf("Listen failed: %v", err) + } + defer ln.Close() + + serverDone := make(chan struct{}) + go func() { + conn, err := ln.Accept() + if err == nil { + conn.Write([]byte("hello")) + conn.Close() + } + close(serverDone) + }() + + client, err := net.Dial("tcp", ln.Addr().String()) + if err != nil { + t.Fatalf("Dial failed: %v", err) + } + defer client.Close() + + tcpConn, ok := client.(*net.TCPConn) + if !ok { + t.Fatalf("expected *net.TCPConn, got %T", client) + } + + sndNxt, rcvNxt, err := readFreeBSDTCPSequence(tcpConn) + if err != nil { + t.Fatalf("readFreeBSDTCPSequence failed: %v", err) + } + + if sndNxt == 0 && rcvNxt == 0 { + t.Errorf("expected non-zero sequence numbers, got sndNxt=%d rcvNxt=%d", sndNxt, rcvNxt) + } + t.Logf("FreeBSD TCP sequence retrieved: snd_nxt=%d, rcv_nxt=%d", sndNxt, rcvNxt) + <-serverDone +} + +func TestFreeBSDRawSocket(t *testing.T) { + u, err := user.Current() + if err == nil && u.Uid != "0" { + t.Skip("skipping test; must be root to open raw sockets") + } + + dst := netip.MustParseAddrPort("8.8.8.8:443") + src := netip.MustParseAddrPort("127.0.0.1:12345") + + fd, sockaddr, err := openFreeBSDRawSocket(src, dst) + if err != nil { + t.Fatalf("openFreeBSDRawSocket failed: %v", err) + } + defer func() { + if fd >= 0 { + unix.Close(fd) + } + }() + + if fd < 0 { + t.Errorf("expected valid fd, got %d", fd) + } + if sockaddr == nil { + t.Error("expected valid sockaddr, got nil") + } +} diff --git a/transport/internet/tls/tlsspoof/spoof_test.go b/transport/internet/tls/tlsspoof/spoof_test.go new file mode 100644 index 000000000000..c51e4fddceb0 --- /dev/null +++ b/transport/internet/tls/tlsspoof/spoof_test.go @@ -0,0 +1,111 @@ +package tlsspoof + +import ( + "testing" +) + +func TestBuildFakeClientHello(t *testing.T) { + hello, err := buildFakeClientHello("www.example.com") + if err != nil { + t.Fatal("buildFakeClientHello returned error:", err) + } + if len(hello) == 0 { + t.Fatal("buildFakeClientHello returned empty payload") + } + // TLS record header: content type 0x16 (handshake) + if hello[0] != 0x16 { + t.Fatalf("expected TLS handshake record type 0x16, got 0x%02x", hello[0]) + } + // TLS version: 0x0301 (TLS 1.0 record layer) + if hello[1] != 0x03 || hello[2] != 0x01 { + t.Fatalf("unexpected TLS record version: 0x%02x%02x", hello[1], hello[2]) + } + t.Logf("ClientHello payload length: %d bytes", len(hello)) +} + +func TestBuildFakeClientHelloEmptySNI(t *testing.T) { + _, err := buildFakeClientHello("") + if err == nil { + t.Fatal("expected error for empty SNI") + } +} + +func TestParseMethod(t *testing.T) { + tests := []struct { + input string + expected Method + hasErr bool + }{ + {"", MethodWrongSequence, false}, + {"wrong-sequence", MethodWrongSequence, false}, + {"wrong-checksum", MethodWrongChecksum, false}, + {"wrong-ack", MethodWrongAcknowledgment, false}, + {"wrong-md5", MethodWrongMD5Sig, false}, + {"wrong-timestamp", MethodWrongTimestamp, false}, + {"invalid", 0, true}, + } + for _, tt := range tests { + m, err := ParseMethod(tt.input) + if tt.hasErr { + if err == nil { + t.Errorf("ParseMethod(%q): expected error, got nil", tt.input) + } + continue + } + if err != nil { + t.Errorf("ParseMethod(%q): unexpected error: %v", tt.input, err) + continue + } + if m != tt.expected { + t.Errorf("ParseMethod(%q) = %v, want %v", tt.input, m, tt.expected) + } + } +} + +func TestParseOptions(t *testing.T) { + // Empty spoof should be a no-op + sni, _, err := ParseOptions("", "") + if err != nil { + t.Fatal("ParseOptions(\"\", \"\"): unexpected error:", err) + } + if sni != "" { + t.Fatalf("expected empty SNI, got %q", sni) + } + + // spoof_method without spoof should error + _, _, err = ParseOptions("", "wrong-checksum") + if err == nil { + t.Fatal("expected error when spoof_method set without spoof") + } + + // Valid combo + sni, method, err := ParseOptions("fake.example.com", "wrong-checksum") + if err != nil { + t.Fatal("ParseOptions: unexpected error:", err) + } + if sni != "fake.example.com" { + t.Fatalf("expected SNI 'fake.example.com', got %q", sni) + } + if method != MethodWrongChecksum { + t.Fatalf("expected MethodWrongChecksum, got %v", method) + } + + // IP-literal should be rejected + _, _, err = ParseOptions("1.2.3.4", "wrong-checksum") + if err == nil { + t.Fatal("expected error for IP-literal spoof") + } + _, _, err = ParseOptions("::1", "wrong-checksum") + if err == nil { + t.Fatal("expected error for IP-literal spoof") + } +} + +func TestMethodString(t *testing.T) { + if MethodWrongSequence.String() != "wrong-sequence" { + t.Fatalf("unexpected method string: %s", MethodWrongSequence.String()) + } + if MethodWrongChecksum.String() != "wrong-checksum" { + t.Fatalf("unexpected method string: %s", MethodWrongChecksum.String()) + } +} diff --git a/transport/internet/tls/tlsspoof/tcpip.go b/transport/internet/tls/tlsspoof/tcpip.go new file mode 100644 index 000000000000..3392704c405a --- /dev/null +++ b/transport/internet/tls/tlsspoof/tcpip.go @@ -0,0 +1,155 @@ +package tlsspoof + +import ( + "encoding/binary" + "net/netip" +) + +const ( + IPv4MinimumSize = 20 + IPv6MinimumSize = 40 + TCPMinimumSize = 20 + TCPProtocolNumber = 6 + + TCPOptionEOL = 0 + TCPOptionNOP = 1 + TCPOptionTS = 8 + TCPOptionTSLength = 10 + + TCPFlagFin = 0x01 + TCPFlagSyn = 0x02 + TCPFlagRst = 0x04 + TCPFlagPsh = 0x08 + TCPFlagAck = 0x10 +) + +func Checksum(data []byte, initial uint16) uint16 { + var csum uint32 = uint32(initial) + for i := 0; i < len(data)-1; i += 2 { + csum += uint32(binary.BigEndian.Uint16(data[i:])) + } + if len(data)%2 == 1 { + csum += uint32(data[len(data)-1]) << 8 + } + for csum > 0xffff { + csum = (csum >> 16) + (csum & 0xffff) + } + return uint16(csum) +} + +func PseudoHeaderChecksum(protocol uint8, srcAddr, dstAddr []byte, totalLen uint16) uint16 { + var csum uint32 + for i := 0; i < len(srcAddr); i += 2 { + csum += uint32(binary.BigEndian.Uint16(srcAddr[i:])) + } + for i := 0; i < len(dstAddr); i += 2 { + csum += uint32(binary.BigEndian.Uint16(dstAddr[i:])) + } + csum += uint32(protocol) + csum += uint32(totalLen) + for csum > 0xffff { + csum = (csum >> 16) + (csum & 0xffff) + } + return uint16(csum) +} + +func CombineChecksum(c1, c2 uint16) uint16 { + csum := uint32(c1) + uint32(c2) + for csum > 0xffff { + csum = (csum >> 16) + (csum & 0xffff) + } + return uint16(csum) +} + +func EncodeTSOption(val uint32, ecr uint32, b []byte) { + b[0] = TCPOptionTS + b[1] = TCPOptionTSLength + binary.BigEndian.PutUint32(b[2:], val) + binary.BigEndian.PutUint32(b[6:], ecr) +} + +func ParseTCPOptions(b []byte) (tsVal uint32, hasTS bool) { + for i := 0; i < len(b); { + if b[i] == TCPOptionEOL { + break + } + if b[i] == TCPOptionNOP { + i++ + continue + } + if i+1 >= len(b) { + break + } + optLen := int(b[i+1]) + if optLen < 2 || i+optLen > len(b) { + break + } + if b[i] == TCPOptionTS && optLen == TCPOptionTSLength { + return binary.BigEndian.Uint32(b[i+2:]), true + } + i += optLen + } + return 0, false +} + +// IPv4 header representation +type IPv4 []byte + +func (b IPv4) TotalLength() uint16 { return binary.BigEndian.Uint16(b[2:]) } +func (b IPv4) Flags() uint8 { return uint8(binary.BigEndian.Uint16(b[6:]) >> 13) } +func (b IPv4) FragmentOffset() uint16 { return binary.BigEndian.Uint16(b[6:]) & 0x1fff } +func (b IPv4) Protocol() uint8 { return b[9] } +func (b IPv4) HeaderLength() uint8 { return (b[0] & 0x0f) * 4 } + +func (b IPv4) Encode(totalLength uint16, id uint16, ttl uint8, protocol uint8, src, dst netip.Addr) { + b[0] = (4 << 4) | 5 // IPv4, Header Length = 20 + b[1] = 0 // TOS + binary.BigEndian.PutUint16(b[2:], totalLength) + binary.BigEndian.PutUint16(b[4:], id) + binary.BigEndian.PutUint16(b[6:], 0) // Flags and Fragment Offset + b[8] = ttl + b[9] = protocol + b[10] = 0 // Checksum (0 for calculation) + copy(b[12:16], src.AsSlice()) + copy(b[16:20], dst.AsSlice()) + csum := Checksum(b[:20], 0) + binary.BigEndian.PutUint16(b[10:], ^csum) +} + +type IPv6 []byte + +func (b IPv6) PayloadLength() uint16 { return binary.BigEndian.Uint16(b[4:]) } +func (b IPv6) TransportProtocol() uint8 { return b[6] } + +func (b IPv6) Encode(payloadLength uint16, transportProtocol uint8, hopLimit uint8, src, dst netip.Addr) { + binary.BigEndian.PutUint32(b[0:], 6<<28) // Version 6, Traffic Class 0, Flow Label 0 + binary.BigEndian.PutUint16(b[4:], payloadLength) + b[6] = transportProtocol + b[7] = hopLimit + copy(b[8:24], src.AsSlice()) + copy(b[24:40], dst.AsSlice()) +} + +type TCP []byte + +func (b TCP) DataOffset() uint8 { return (b[12] >> 4) * 4 } +func (b TCP) SequenceNumber() uint32 { return binary.BigEndian.Uint32(b[4:]) } +func (b TCP) AckNumber() uint32 { return binary.BigEndian.Uint32(b[8:]) } +func (b TCP) Options() []byte { return b[TCPMinimumSize:b.DataOffset()] } +func (b TCP) SetChecksum(csum uint16) { binary.BigEndian.PutUint16(b[16:], csum) } + +func (b TCP) Encode(srcPort, dstPort uint16, seqNum, ackNum uint32, dataOffset uint8, flags uint8, windowSize uint16) { + binary.BigEndian.PutUint16(b[0:], srcPort) + binary.BigEndian.PutUint16(b[2:], dstPort) + binary.BigEndian.PutUint32(b[4:], seqNum) + binary.BigEndian.PutUint32(b[8:], ackNum) + b[12] = (dataOffset / 4) << 4 + b[13] = flags + binary.BigEndian.PutUint16(b[14:], windowSize) + b[16] = 0 // Checksum + binary.BigEndian.PutUint16(b[18:], 0) // Urgent pointer +} + +func (b TCP) CalculateChecksum(initial uint16) uint16 { + return Checksum(b, initial) +} diff --git a/transport/internet/tls/tlsspoof/windivert/assets/LICENSE.txt b/transport/internet/tls/tlsspoof/windivert/assets/LICENSE.txt new file mode 100644 index 000000000000..8489a8e773c3 --- /dev/null +++ b/transport/internet/tls/tlsspoof/windivert/assets/LICENSE.txt @@ -0,0 +1,1191 @@ +WinDivert is dual-licensed under your choice of the GNU Lesser General Public +License (LGPL) Version 3 or the GNU General Public License (GPL) Version 2. +Copies of the LGPLv3, GPLv3 and GPLv2 are provided below. + +============================================================================== + + GNU LESSER GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + + This version of the GNU Lesser General Public License incorporates +the terms and conditions of version 3 of the GNU General Public +License, supplemented by the additional permissions listed below. + + 0. Additional Definitions. + + As used herein, "this License" refers to version 3 of the GNU Lesser +General Public License, and the "GNU GPL" refers to version 3 of the GNU +General Public License. + + "The Library" refers to a covered work governed by this License, +other than an Application or a Combined Work as defined below. + + An "Application" is any work that makes use of an interface provided +by the Library, but which is not otherwise based on the Library. +Defining a subclass of a class defined by the Library is deemed a mode +of using an interface provided by the Library. + + A "Combined Work" is a work produced by combining or linking an +Application with the Library. The particular version of the Library +with which the Combined Work was made is also called the "Linked +Version". + + The "Minimal Corresponding Source" for a Combined Work means the +Corresponding Source for the Combined Work, excluding any source code +for portions of the Combined Work that, considered in isolation, are +based on the Application, and not on the Linked Version. + + The "Corresponding Application Code" for a Combined Work means the +object code and/or source code for the Application, including any data +and utility programs needed for reproducing the Combined Work from the +Application, but excluding the System Libraries of the Combined Work. + + 1. Exception to Section 3 of the GNU GPL. + + You may convey a covered work under sections 3 and 4 of this License +without being bound by section 3 of the GNU GPL. + + 2. Conveying Modified Versions. + + If you modify a copy of the Library, and, in your modifications, a +facility refers to a function or data to be supplied by an Application +that uses the facility (other than as an argument passed when the +facility is invoked), then you may convey a copy of the modified +version: + + a) under this License, provided that you make a good faith effort to + ensure that, in the event an Application does not supply the + function or data, the facility still operates, and performs + whatever part of its purpose remains meaningful, or + + b) under the GNU GPL, with none of the additional permissions of + this License applicable to that copy. + + 3. Object Code Incorporating Material from Library Header Files. + + The object code form of an Application may incorporate material from +a header file that is part of the Library. You may convey such object +code under terms of your choice, provided that, if the incorporated +material is not limited to numerical parameters, data structure +layouts and accessors, or small macros, inline functions and templates +(ten or fewer lines in length), you do both of the following: + + a) Give prominent notice with each copy of the object code that the + Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the object code with a copy of the GNU GPL and this license + document. + + 4. Combined Works. + + You may convey a Combined Work under terms of your choice that, +taken together, effectively do not restrict modification of the +portions of the Library contained in the Combined Work and reverse +engineering for debugging such modifications, if you also do each of +the following: + + a) Give prominent notice with each copy of the Combined Work that + the Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the Combined Work with a copy of the GNU GPL and this license + document. + + c) For a Combined Work that displays copyright notices during + execution, include the copyright notice for the Library among + these notices, as well as a reference directing the user to the + copies of the GNU GPL and this license document. + + d) Do one of the following: + + 0) Convey the Minimal Corresponding Source under the terms of this + License, and the Corresponding Application Code in a form + suitable for, and under terms that permit, the user to + recombine or relink the Application with a modified version of + the Linked Version to produce a modified Combined Work, in the + manner specified by section 6 of the GNU GPL for conveying + Corresponding Source. + + 1) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (a) uses at run time + a copy of the Library already present on the user's computer + system, and (b) will operate properly with a modified version + of the Library that is interface-compatible with the Linked + Version. + + e) Provide Installation Information, but only if you would otherwise + be required to provide such information under section 6 of the + GNU GPL, and only to the extent that such information is + necessary to install and execute a modified version of the + Combined Work produced by recombining or relinking the + Application with a modified version of the Linked Version. (If + you use option 4d0, the Installation Information must accompany + the Minimal Corresponding Source and Corresponding Application + Code. If you use option 4d1, you must provide the Installation + Information in the manner specified by section 6 of the GNU GPL + for conveying Corresponding Source.) + + 5. Combined Libraries. + + You may place library facilities that are a work based on the +Library side by side in a single library together with other library +facilities that are not Applications and are not covered by this +License, and convey such a combined library under terms of your +choice, if you do both of the following: + + a) Accompany the combined library with a copy of the same work based + on the Library, uncombined with any other library facilities, + conveyed under the terms of this License. + + b) Give prominent notice with the combined library that part of it + is a work based on the Library, and explaining where to find the + accompanying uncombined form of the same work. + + 6. Revised Versions of the GNU Lesser General Public License. + + The Free Software Foundation may publish revised and/or new versions +of the GNU Lesser General Public License from time to time. Such new +versions will be similar in spirit to the present version, but may +differ in detail to address new problems or concerns. + + Each version is given a distinguishing version number. If the +Library as you received it specifies that a certain numbered version +of the GNU Lesser General Public License "or any later version" +applies to it, you have the option of following the terms and +conditions either of that published version or of any later version +published by the Free Software Foundation. If the Library as you +received it does not specify a version number of the GNU Lesser +General Public License, you may choose any version of the GNU Lesser +General Public License ever published by the Free Software Foundation. + + If the Library as you received it specifies that a proxy can decide +whether future versions of the GNU Lesser General Public License shall +apply, that proxy's public statement of acceptance of any version is +permanent authorization for you to choose that version for the +Library. + +============================================================================== + + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. + +============================================================================== + + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. + diff --git a/transport/internet/tls/tlsspoof/windivert/assets/WinDivert32.sys b/transport/internet/tls/tlsspoof/windivert/assets/WinDivert32.sys new file mode 100644 index 000000000000..d06738cbb783 Binary files /dev/null and b/transport/internet/tls/tlsspoof/windivert/assets/WinDivert32.sys differ diff --git a/transport/internet/tls/tlsspoof/windivert/assets/WinDivert64.sys b/transport/internet/tls/tlsspoof/windivert/assets/WinDivert64.sys new file mode 100644 index 000000000000..218ccaf423ef Binary files /dev/null and b/transport/internet/tls/tlsspoof/windivert/assets/WinDivert64.sys differ diff --git a/transport/internet/tls/tlsspoof/windivert/assets_386.go b/transport/internet/tls/tlsspoof/windivert/assets_386.go new file mode 100644 index 000000000000..0cbf35ed5cbf --- /dev/null +++ b/transport/internet/tls/tlsspoof/windivert/assets_386.go @@ -0,0 +1,14 @@ +//go:build windows && 386 + +package windivert + +import _ "embed" + +//go:embed assets/WinDivert32.sys +var sysBytes []byte + +func assetFiles() []assetFile { + return []assetFile{{"WinDivert32.sys", sysBytes}} +} + +func driverSysName() string { return "WinDivert32.sys" } diff --git a/transport/internet/tls/tlsspoof/windivert/assets_amd64.go b/transport/internet/tls/tlsspoof/windivert/assets_amd64.go new file mode 100644 index 000000000000..2c9fb6c6ad19 --- /dev/null +++ b/transport/internet/tls/tlsspoof/windivert/assets_amd64.go @@ -0,0 +1,14 @@ +//go:build windows && amd64 + +package windivert + +import _ "embed" + +//go:embed assets/WinDivert64.sys +var sysBytes []byte + +func assetFiles() []assetFile { + return []assetFile{{"WinDivert64.sys", sysBytes}} +} + +func driverSysName() string { return "WinDivert64.sys" } diff --git a/transport/internet/tls/tlsspoof/windivert/assets_unsupported.go b/transport/internet/tls/tlsspoof/windivert/assets_unsupported.go new file mode 100644 index 000000000000..04698953fa6b --- /dev/null +++ b/transport/internet/tls/tlsspoof/windivert/assets_unsupported.go @@ -0,0 +1,7 @@ +//go:build windows && !amd64 && !386 + +package windivert + +func assetFiles() []assetFile { return nil } + +func driverSysName() string { return "" } diff --git a/transport/internet/tls/tlsspoof/windivert/driver_windows.go b/transport/internet/tls/tlsspoof/windivert/driver_windows.go new file mode 100644 index 000000000000..50e94c578422 --- /dev/null +++ b/transport/internet/tls/tlsspoof/windivert/driver_windows.go @@ -0,0 +1,211 @@ +//go:build windows + +package windivert + +import ( + "errors" + "fmt" + "os" + "path/filepath" + "runtime" + "strconv" + "sync" + + "golang.org/x/sys/windows" +) + +const ( + driverServiceName = "WinDivert" + driverDeviceName = `\\.\WinDivert` +) + +var ( + driverOnce sync.Once + driverErr error + // driverDevName is ASCII-safe and must be available before ensureDriver + // so Open can try CreateFile first and only install on FILE_NOT_FOUND. + driverDevName, _ = windows.UTF16PtrFromString(driverDeviceName) +) + +// Requires SeLoadDriverPrivilege (Administrator). Running the 386 build +// under WOW64 on a 64-bit kernel is rejected — use the amd64 build. +func ensureDriver() error { + driverOnce.Do(func() { + driverErr = installDriver() + }) + return driverErr +} + +func installDriver() error { + if runtime.GOARCH == "386" { + var isWow64 bool + err := windows.IsWow64Process(windows.CurrentProcess(), &isWow64) + if err == nil && isWow64 { + return errors.New("windivert: 386 build detected running under WOW64 on a 64-bit kernel; use the amd64 build") + } + } + + dir, err := ensureExtracted() + if err != nil { + return err + } + sysPath := filepath.Join(dir, driverSysName()) + sysPathW, err := windows.UTF16PtrFromString(sysPath) + if err != nil { + return fmt.Errorf("windivert: utf16 driver path: %w", err) + } + + // Serialize driver install across concurrent processes. + mutexName, _ := windows.UTF16PtrFromString("WinDivertDriverInstallMutex") + mutex, err := windows.CreateMutex(nil, false, mutexName) + if err != nil { + return fmt.Errorf("windivert: create install mutex: %w", err) + } + defer windows.CloseHandle(mutex) + _, err = windows.WaitForSingleObject(mutex, windows.INFINITE) + if err != nil { + return fmt.Errorf("windivert: wait install mutex: %w", err) + } + defer windows.ReleaseMutex(mutex) + + manager, err := windows.OpenSCManager(nil, nil, windows.SC_MANAGER_ALL_ACCESS) + if err != nil { + return fmt.Errorf("windivert: open SCM: %w", err) + } + defer windows.CloseServiceHandle(manager) + + serviceNameW, _ := windows.UTF16PtrFromString(driverServiceName) + service, err := windows.OpenService(manager, serviceNameW, windows.SERVICE_ALL_ACCESS) + if err != nil { + service, err = windows.CreateService( + manager, + serviceNameW, + serviceNameW, + windows.SERVICE_ALL_ACCESS, + windows.SERVICE_KERNEL_DRIVER, + windows.SERVICE_DEMAND_START, + windows.SERVICE_ERROR_NORMAL, + sysPathW, + nil, nil, nil, nil, nil, + ) + if err != nil { + if errors.Is(err, windows.ERROR_SERVICE_EXISTS) { + service, err = windows.OpenService(manager, serviceNameW, windows.SERVICE_ALL_ACCESS) + } + if err != nil { + return wrapDriverInstallError(err) + } + } + } + defer windows.CloseServiceHandle(service) + + err = windows.StartService(service, 0, nil) + if err != nil && errors.Is(err, windows.ERROR_SERVICE_DISABLED) { + // A prior process called DeleteService on a still-running kernel + // driver: SCM marks the record for deletion and flips START_TYPE + // to DISABLED until the last handle closes. Re-enable so we can + // start it instead of waiting for a reboot. + err = windows.ChangeServiceConfig( + service, + windows.SERVICE_NO_CHANGE, + windows.SERVICE_DEMAND_START, + windows.SERVICE_NO_CHANGE, + nil, nil, nil, nil, nil, nil, nil, + ) + if err != nil { + return fmt.Errorf("windivert: re-enable disabled service: %w", err) + } + err = windows.StartService(service, 0, nil) + } + if err == nil { + // Mark for deletion so the driver unregisters when the last handle + // closes or on next reboot. Matches the upstream DLL's behavior: + // only the process that actually started the service takes on the + // cleanup responsibility. If another process already started it, + // we leave DeleteService to them. + _ = windows.DeleteService(service) + } else if !errors.Is(err, windows.ERROR_SERVICE_ALREADY_RUNNING) { + return fmt.Errorf("windivert: start service: %w", err) + } + return nil +} + +func wrapDriverInstallError(err error) error { + if errors.Is(err, windows.ERROR_ACCESS_DENIED) { + return fmt.Errorf("windivert: installing the kernel driver requires Administrator privileges: %w", err) + } + return fmt.Errorf("windivert: create service: %w", err) +} + +type assetFile struct { + name string + data []byte +} + +var ( + extractOnce sync.Once + extractErr error + extractDir string +) + +// The on-disk copy is protected by Windows Authenticode signature +// enforcement, which rejects any tampered .sys at StartService time. +func ensureExtracted() (string, error) { + extractOnce.Do(func() { + extractDir, extractErr = extractImpl() + }) + return extractDir, extractErr +} + +func extractImpl() (string, error) { + files := assetFiles() + if len(files) == 0 { + return "", fmt.Errorf("windivert: unsupported architecture %s", runtime.GOARCH) + } + + base, err := os.UserCacheDir() + if err != nil { + return "", fmt.Errorf("windivert: locate user cache dir: %w", err) + } + dir := filepath.Join(base, "xray-core", "windivert", "v"+AssetVersion) + err = os.MkdirAll(dir, 0o755) + if err != nil { + return "", fmt.Errorf("windivert: mkdir %s: %w", dir, err) + } + + for _, asset := range files { + err = ensureAsset(dir, asset) + if err != nil { + return "", err + } + } + return dir, nil +} + +// Concurrent sing-box processes race on os.Rename (atomic on NTFS); +// whichever wins creates the final file. Writers that lose the race +// silently discard their temp copy. +func ensureAsset(dir string, asset assetFile) error { + target := filepath.Join(dir, asset.name) + _, err := os.Stat(target) + if err == nil { + return nil + } + if !os.IsNotExist(err) { + return fmt.Errorf("windivert: stat %s: %w", asset.name, err) + } + tmp := target + ".tmp-" + strconv.Itoa(os.Getpid()) + err = os.WriteFile(tmp, asset.data, 0o644) + if err != nil { + return fmt.Errorf("windivert: write %s: %w", asset.name, err) + } + err = os.Rename(tmp, target) + if err != nil { + os.Remove(tmp) + if _, statErr := os.Stat(target); statErr == nil { + return nil + } + return fmt.Errorf("windivert: rename %s: %w", asset.name, err) + } + return nil +} diff --git a/transport/internet/tls/tlsspoof/windivert/filter.go b/transport/internet/tls/tlsspoof/windivert/filter.go new file mode 100644 index 000000000000..d63adae2b630 --- /dev/null +++ b/transport/internet/tls/tlsspoof/windivert/filter.go @@ -0,0 +1,181 @@ +package windivert + +import ( + "encoding/binary" + "errors" + "net/netip" +) + +// WINDIVERT_FILTER VM instruction layout (24 bytes, #pragma pack(1)): +// +// word 0 (LE): field:11 | test:5 | success:16 +// word 1 (LE): failure:16 | neg:1 | reserved:15 +// words 2..5: arg[4] (native-endian uint32 each) +// +// The driver walks this as a decision tree: evaluate the test at inst i; +// on success jump to success; on failure jump to failure. Continuations +// 0x7FFE and 0x7FFF are ACCEPT and REJECT terminals. +const ( + filterInstBytes = 24 + filterMaxInsts = 256 + + fieldZero = 0 + fieldOutbound = 2 + fieldIP = 5 + fieldIPv6 = 6 + fieldTCP = 8 + fieldIPSrcAddr = 21 + fieldIPDstAddr = 22 + fieldIPv6SrcAddr = 28 + fieldIPv6DstAddr = 29 + fieldTCPSrcPort = 38 + fieldTCPDstPort = 39 + + testEQ = 0 + + resultAccept uint16 = 0x7FFE + resultReject uint16 = 0x7FFF +) + +// Filter flags passed to IOCTL_WINDIVERT_STARTUP alongside the compiled +// filter. These tell the driver what *kinds* of packets the filter might +// match, used as a kernel-side fast-reject. +const ( + filterFlagOutbound uint64 = 0x0020 + filterFlagIP uint64 = 0x0040 + filterFlagIPv6 uint64 = 0x0080 +) + +type filterInst struct { + field uint16 // 11 bits used + test uint8 // 5 bits used + success uint16 + failure uint16 + neg bool + arg [4]uint32 +} + +// Filter is a typed specification of packets to capture. It replaces +// WinDivert's filter string language. +// +// Zero value = "reject all" (match nothing), suitable for send-only handles. +type Filter struct { + insts []filterInst + flags uint64 // filter flags for STARTUP ioctl +} + +// reject returns a filter that matches no packet. The empty insts slice +// is encoded as a single rejecting instruction by encode(). +func reject() *Filter { + return &Filter{} +} + +// OutboundTCP returns a filter matching outbound TCP packets on the given +// 5-tuple. Both addresses must share an address family (IPv4 or IPv6). +func OutboundTCP(src, dst netip.AddrPort) (*Filter, error) { + if !src.IsValid() || !dst.IsValid() { + return nil, errors.New("windivert: filter: invalid address port") + } + if src.Addr().Is4() != dst.Addr().Is4() { + return nil, errors.New("windivert: filter: mixed IPv4/IPv6") + } + f := &Filter{ + flags: filterFlagOutbound, + } + // Insts chain as AND: each test's failure = REJECT, success = next inst. + // The final inst's success = ACCEPT. + f.add(fieldOutbound, testEQ, argUint32(1)) + if src.Addr().Is4() { + f.flags |= filterFlagIP + f.add(fieldIP, testEQ, argUint32(1)) + f.add(fieldTCP, testEQ, argUint32(1)) + f.add(fieldIPSrcAddr, testEQ, argIPv4(src.Addr())) + f.add(fieldIPDstAddr, testEQ, argIPv4(dst.Addr())) + } else { + f.flags |= filterFlagIPv6 + f.add(fieldIPv6, testEQ, argUint32(1)) + f.add(fieldTCP, testEQ, argUint32(1)) + f.add(fieldIPv6SrcAddr, testEQ, argIPv6(src.Addr())) + f.add(fieldIPv6DstAddr, testEQ, argIPv6(dst.Addr())) + } + f.add(fieldTCPSrcPort, testEQ, argUint32(uint32(src.Port()))) + f.add(fieldTCPDstPort, testEQ, argUint32(uint32(dst.Port()))) + return f, nil +} + +func (f *Filter) add(field uint16, test uint8, arg [4]uint32) { + f.insts = append(f.insts, filterInst{field: field, test: test, arg: arg}) +} + +func argUint32(v uint32) [4]uint32 { return [4]uint32{v, 0, 0, 0} } + +// argIPv4 encodes an IPv4 address for IP_SRCADDR/IP_DSTADDR. The driver +// compares against an IPv4-mapped-IPv6 form: {host_order_u32, 0x0000FFFF, +// 0, 0} (see sys/windivert.c windivert_get_ipv4_addr and the IPv4_SRCADDR +// val-word construction). Omitting the 0x0000FFFF marker causes the EQ +// test to fail for every packet. +func argIPv4(addr netip.Addr) [4]uint32 { + b := addr.As4() + return [4]uint32{binary.BigEndian.Uint32(b[:]), 0x0000FFFF, 0, 0} +} + +// argIPv6 encodes an IPv6 address for IPV6_SRCADDR/IPV6_DSTADDR. The +// driver stores the address as four host-order uint32s in REVERSED word +// order: val[0]=low (bytes 12..15), val[3]=high (bytes 0..3). See +// sys/windivert.c windivert_outbound_network_v6_classify val-word +// construction. +func argIPv6(addr netip.Addr) [4]uint32 { + b := addr.As16() + return [4]uint32{ + binary.BigEndian.Uint32(b[12:16]), + binary.BigEndian.Uint32(b[8:12]), + binary.BigEndian.Uint32(b[4:8]), + binary.BigEndian.Uint32(b[0:4]), + } +} + +// encode serializes the Filter to the on-wire WINDIVERT_FILTER[] format +// plus the filter_flags for STARTUP ioctl. +func (f *Filter) encode() ([]byte, uint64, error) { + if len(f.insts) == 0 { + // "Reject all" — one instruction, ZERO == 0 is always true, but we + // invert by setting both success and failure to REJECT. + return encodeInst(filterInst{ + field: fieldZero, + test: testEQ, + success: resultReject, + failure: resultReject, + }), 0, nil + } + if len(f.insts) > filterMaxInsts-1 { + return nil, 0, errors.New("windivert: filter too long") + } + buf := make([]byte, 0, filterInstBytes*len(f.insts)) + for i, inst := range f.insts { + if i == len(f.insts)-1 { + inst.success = resultAccept + } else { + inst.success = uint16(i + 1) + } + inst.failure = resultReject + buf = append(buf, encodeInst(inst)...) + } + return buf, f.flags, nil +} + +func encodeInst(inst filterInst) []byte { + out := make([]byte, filterInstBytes) + word0 := uint32(inst.field&0x7FF) | uint32(inst.test&0x1F)<<11 | + uint32(inst.success)<<16 + word1 := uint32(inst.failure) + if inst.neg { + word1 |= 1 << 16 + } + binary.LittleEndian.PutUint32(out[0:4], word0) + binary.LittleEndian.PutUint32(out[4:8], word1) + binary.LittleEndian.PutUint32(out[8:12], inst.arg[0]) + binary.LittleEndian.PutUint32(out[12:16], inst.arg[1]) + binary.LittleEndian.PutUint32(out[16:20], inst.arg[2]) + binary.LittleEndian.PutUint32(out[20:24], inst.arg[3]) + return out +} diff --git a/transport/internet/tls/tlsspoof/windivert/handle_windows.go b/transport/internet/tls/tlsspoof/windivert/handle_windows.go new file mode 100644 index 000000000000..c48e6214c11b --- /dev/null +++ b/transport/internet/tls/tlsspoof/windivert/handle_windows.go @@ -0,0 +1,323 @@ +//go:build windows + +package windivert + +import ( + "encoding/binary" + "errors" + "fmt" + "runtime" + "sync" + "unsafe" + + "golang.org/x/sys/windows" +) + +// Handle owns a WinDivert kernel device handle plus a private event for +// overlapped I/O. Methods on *Handle are not safe for concurrent use +// across goroutines (there is a single shared event per Handle). +// +// addr is a per-Handle Address buffer the IOCTL struct embeds a pointer +// to. It lives on the heap (as a field of a heap-allocated Handle) so +// the pointer value stored as bytes in the ioctl buffer remains valid +// across stack growth between buildIoctl* and the DeviceIoControl +// syscall — stack-local Address values are not safe for this pattern +// because Go's escape analysis does not see the pointer through the +// unsafe.Pointer → uintptr → bytes conversion. +type Handle struct { + device windows.Handle + event windows.Handle + closing sync.Once + closeErr error + addr Address +} + +// Filter may be nil for "reject all", suitable for send-only handles. +// Requires Administrator on first call per process (installs the kernel +// driver via SCM); subsequent calls reuse the running driver. +func Open(filter *Filter, layer Layer, priority int16, flags Flag) (*Handle, error) { + err := validateOpenArgs(layer, priority, flags) + if err != nil { + return nil, err + } + if filter == nil { + filter = reject() + } + filterBin, filterFlags, err := filter.encode() + if err != nil { + return nil, err + } + device, err := openDevice() + if err != nil { + if !errors.Is(err, windows.ERROR_FILE_NOT_FOUND) && + !errors.Is(err, windows.ERROR_PATH_NOT_FOUND) { + if errors.Is(err, windows.ERROR_ACCESS_DENIED) { + return nil, fmt.Errorf("windivert: open device (administrator required): %w", err) + } + return nil, fmt.Errorf("windivert: open device: %w", err) + } + // Device node missing: kernel driver not loaded. Install + retry. + // Matches WinDivertOpen's lazy-install path; avoids racing StartService + // against a still-loaded driver whose SCM record is marked for deletion. + err = ensureDriver() + if err != nil { + return nil, err + } + device, err = openDevice() + if err != nil { + if errors.Is(err, windows.ERROR_ACCESS_DENIED) { + return nil, fmt.Errorf("windivert: open device (administrator required): %w", err) + } + return nil, fmt.Errorf("windivert: open device: %w", err) + } + } + event, err := windows.CreateEvent(nil, 1, 0, nil) // manual reset, unsignaled + if err != nil { + windows.CloseHandle(device) + return nil, fmt.Errorf("windivert: create event: %w", err) + } + h := &Handle{device: device, event: event} + + err = h.initialize(layer, priority, flags) + if err != nil { + h.Close() + return nil, err + } + err = h.startup(filterBin, filterFlags) + if err != nil { + h.Close() + return nil, err + } + return h, nil +} + +func openDevice() (windows.Handle, error) { + return windows.CreateFile( + driverDevName, + windows.GENERIC_READ|windows.GENERIC_WRITE, + 0, nil, + windows.OPEN_EXISTING, + windows.FILE_ATTRIBUTE_NORMAL|windows.FILE_FLAG_OVERLAPPED, + 0, + ) +} + +func validateOpenArgs(layer Layer, priority int16, flags Flag) error { + if layer != LayerNetwork { + return fmt.Errorf("windivert: invalid layer %d", uint32(layer)) + } + if priority < PriorityLowest || priority > PriorityHighest { + return errors.New("windivert: priority out of range") + } + const supportedFlags = FlagSniff | FlagSendOnly + if flags&^supportedFlags != 0 { + return errors.New("windivert: unknown flag bits") + } + if flags&FlagSniff != 0 && flags&FlagSendOnly != 0 { + return errors.New("windivert: FlagSniff and FlagSendOnly are mutually exclusive") + } + return nil +} + +func (h *Handle) initialize(layer Layer, priority int16, flags Flag) error { + in := buildIoctlInitialize(layer, priority, flags) + // WINDIVERT_VERSION is a 64-byte packed struct; only the first 20 + // bytes (magic, major, minor, bits) carry data, the rest is reserved. + var outBuf [versionStructSize]byte + binary.LittleEndian.PutUint64(outBuf[0:8], magicDLL) + binary.LittleEndian.PutUint32(outBuf[8:12], versionMajor) + binary.LittleEndian.PutUint32(outBuf[12:16], versionMinor) + binary.LittleEndian.PutUint32(outBuf[16:20], uint32(unsafe.Sizeof(uintptr(0))*8)) + _, err := doIoctl(h.device, ioctlInitialize, in[:], outBuf[:], h.event) + if err != nil { + return fmt.Errorf("windivert: initialize ioctl: %w", err) + } + gotMagic := binary.LittleEndian.Uint64(outBuf[0:8]) + if gotMagic != magicSYS { + return fmt.Errorf("windivert: driver magic mismatch (got %d)", gotMagic) + } + gotMajor := binary.LittleEndian.Uint32(outBuf[8:12]) + if gotMajor < versionMajor { + gotMinor := binary.LittleEndian.Uint32(outBuf[12:16]) + return fmt.Errorf("windivert: driver version too old: %d.%d", gotMajor, gotMinor) + } + return nil +} + +func (h *Handle) startup(filterBin []byte, filterFlags uint64) error { + in := buildIoctlStartup(filterFlags) + _, err := doIoctl(h.device, ioctlStartup, in[:], filterBin, h.event) + if err != nil { + return fmt.Errorf("windivert: startup ioctl: %w", err) + } + return nil +} + +// If the handle is closed mid-Recv the error wraps ERROR_OPERATION_ABORTED. +func (h *Handle) Recv(buf []byte) (int, Address, error) { + if len(buf) == 0 { + return 0, Address{}, errors.New("windivert: recv: zero-length buffer") + } + h.addr = Address{} + in := buildIoctlRecv(&h.addr) + n, err := doIoctl(h.device, ioctlRecv, in[:], buf, h.event) + runtime.KeepAlive(h) + if err != nil { + return 0, Address{}, err + } + return int(n), h.addr, nil +} + +// The address's Outbound flag controls whether the packet is sent toward +// the wire (outbound=true) or delivered up the stack (outbound=false). +// IfIdx and SubIfIdx can stay zero — the driver uses the routing table +// when IfIdx=0. +func (h *Handle) Send(packet []byte, addr *Address) (int, error) { + if len(packet) == 0 { + return 0, errors.New("windivert: send: empty packet") + } + if addr == nil { + return 0, errors.New("windivert: send: nil address") + } + h.addr = *addr + in := buildIoctlSend(&h.addr) + n, err := doIoctl(h.device, ioctlSend, in[:], packet, h.event) + runtime.KeepAlive(h) + if err != nil { + return 0, err + } + return int(n), nil +} + +// Idempotent. Aborts any in-flight I/O on the handle. +func (h *Handle) Close() error { + h.closing.Do(func() { + var errs []error + if h.device != 0 { + err := windows.CloseHandle(h.device) + if err != nil { + errs = append(errs, err) + } + h.device = 0 + } + if h.event != 0 { + err := windows.CloseHandle(h.event) + if err != nil { + errs = append(errs, err) + } + h.event = 0 + } + h.closeErr = errors.Join(errs...) + }) + return h.closeErr +} + +// IOCTL codes from windivert_device.h. CTL_CODE macro layout: +// +// (DeviceType << 16) | (Access << 14) | (Function << 2) | Method +const ( + fileDeviceNetwork uint32 = 0x12 + accessReadWrite uint32 = 3 // FILE_READ_DATA | FILE_WRITE_DATA + accessRead uint32 = 1 + + methodInDirect uint32 = 1 + methodOutDirect uint32 = 2 +) + +func ctlCode(deviceType, access, function, method uint32) uint32 { + return (deviceType << 16) | (access << 14) | (function << 2) | method +} + +var ( + ioctlInitialize = ctlCode(fileDeviceNetwork, accessReadWrite, 0x921, methodOutDirect) + ioctlStartup = ctlCode(fileDeviceNetwork, accessReadWrite, 0x922, methodInDirect) + ioctlRecv = ctlCode(fileDeviceNetwork, accessRead, 0x923, methodOutDirect) + ioctlSend = ctlCode(fileDeviceNetwork, accessReadWrite, 0x924, methodInDirect) +) + +// Magic numbers exchanged during INITIALIZE. DLL sends magicDLL in the +// version struct; driver returns magicSYS on success. +const ( + magicDLL uint64 = 0x4C4C447669645724 // "$WdivDLL" in LE bytes + magicSYS uint64 = 0x5359537669645723 // "#WdivSYS" in LE bytes +) + +const ( + versionMajor uint32 = 2 + versionMinor uint32 = 2 +) + +// Size of the WINDIVERT_IOCTL union on wire (packed). +const ioctlSize = 16 + +// Size of WINDIVERT_VERSION on wire (packed). Only the first 20 bytes +// carry data; the rest is reserved zero padding. +const versionStructSize = 64 + +// doIoctl performs a single synchronous (blocking) overlapped +// DeviceIoControl. The handle is opened with FILE_FLAG_OVERLAPPED so +// DeviceIoControl returns ERROR_IO_PENDING; we then wait for completion +// via GetOverlappedResult. Event is passed in so callers can reuse it +// across calls on the same handle (avoids per-call CreateEvent). +func doIoctl(handle windows.Handle, code uint32, in []byte, out []byte, event windows.Handle) (uint32, error) { + var overlapped windows.Overlapped + overlapped.HEvent = event + _ = windows.ResetEvent(event) + + var inPtr *byte + var inLen uint32 + if len(in) > 0 { + inPtr = &in[0] + inLen = uint32(len(in)) + } + var outPtr *byte + var outLen uint32 + if len(out) > 0 { + outPtr = &out[0] + outLen = uint32(len(out)) + } + var returned uint32 + err := windows.DeviceIoControl(handle, code, inPtr, inLen, outPtr, outLen, &returned, &overlapped) + if err != nil && !errors.Is(err, windows.ERROR_IO_PENDING) { + return 0, err + } + err = windows.GetOverlappedResult(handle, &overlapped, &returned, true) + if err != nil { + return 0, err + } + return returned, nil +} + +func buildIoctlInitialize(layer Layer, priority int16, flags Flag) [ioctlSize]byte { + var buf [ioctlSize]byte + binary.LittleEndian.PutUint32(buf[0:4], uint32(layer)) + // The driver expects priority + WINDIVERT_PRIORITY_HIGHEST (30000) so + // the low range maps to non-negative integers. + binary.LittleEndian.PutUint32(buf[4:8], uint32(int32(priority)+int32(PriorityHighest))) + binary.LittleEndian.PutUint64(buf[8:16], uint64(flags)) + return buf +} + +func buildIoctlStartup(filterFlags uint64) [ioctlSize]byte { + var buf [ioctlSize]byte + binary.LittleEndian.PutUint64(buf[0:8], filterFlags) + return buf +} + +// buildIoctlRecv packs a user-space pointer to a WINDIVERT_ADDRESS into +// the ioctl struct. The driver dereferences it to write the address for +// the received packet. Caller must keep the Address alive via +// runtime.KeepAlive. +func buildIoctlRecv(addr *Address) [ioctlSize]byte { + var buf [ioctlSize]byte + binary.LittleEndian.PutUint64(buf[0:8], uint64(uintptr(unsafe.Pointer(addr)))) + binary.LittleEndian.PutUint64(buf[8:16], 0) + return buf +} + +func buildIoctlSend(addr *Address) [ioctlSize]byte { + var buf [ioctlSize]byte + binary.LittleEndian.PutUint64(buf[0:8], uint64(uintptr(unsafe.Pointer(addr)))) + binary.LittleEndian.PutUint64(buf[8:16], uint64(unsafe.Sizeof(Address{}))) + return buf +} diff --git a/transport/internet/tls/tlsspoof/windivert/windivert.go b/transport/internet/tls/tlsspoof/windivert/windivert.go new file mode 100644 index 000000000000..9d309886cbe3 --- /dev/null +++ b/transport/internet/tls/tlsspoof/windivert/windivert.go @@ -0,0 +1,78 @@ +// Package windivert provides a pure-Go binding to the WinDivert kernel +// driver on Windows (amd64 and 386). User-mode WinDivert calls are +// reimplemented in Go; only the signed kernel driver is embedded as an +// asset, since SCM-installed drivers must live on disk and their +// Authenticode signature forbids modification. +// +// Administrator is required for the first Open in a process so SCM can +// load the driver. Upstream: https://github.com/basil00/WinDivert v2.2.2, +// redistributed under its LGPL v3 option; see assets/LICENSE.txt. +package windivert + +import "unsafe" + +const AssetVersion = "2.2.2" + +// MTUMax is WINDIVERT_MTU_MAX from windivert.h (40 + 0xFFFF). Suitable as +// a single-packet receive buffer size. +const MTUMax = 40 + 0xFFFF + +type Layer uint32 + +const LayerNetwork Layer = 0 + +type Flag uint64 + +const ( + // FlagSniff opens a passive observer: the driver copies matching packets + // to userspace without removing them from the network stack. Send is not + // required (and not allowed) on a sniffing handle. + FlagSniff Flag = 0x0001 + // FlagSendOnly opens a write-only injection handle; Recv is not allowed. + FlagSendOnly Flag = 0x0008 +) + +const ( + PriorityHighest int16 = 30000 + PriorityLowest int16 = -30000 +) + +// Address mirrors WINDIVERT_ADDRESS from windivert.h (80 bytes, +// little-endian on both amd64 and 386): +// +// 0: INT64 Timestamp +// 8: UINT32 bitfield: Layer:8 | Event:8 | flags | Reserved1:8 +// 12: UINT32 Reserved2 +// 16: 64 bytes union (WINDIVERT_DATA_NETWORK / FLOW / SOCKET / REFLECT) +type Address struct { + Timestamp int64 + bits uint32 + Reserved2 uint32 + union [64]byte +} + +var _ [80]byte = [unsafe.Sizeof(Address{})]byte{} + +// Bit positions inside the Address's packed flags word. +const ( + addrBitIPv6 = 20 + addrBitIPChecksum = 21 + addrBitTCPChecksum = 22 +) + +func getFlagBit(bits uint32, pos uint) bool { return bits&(1<