Merge pull request #2606 from v2fly/master

merge fly
pull/2623/head
Kslr 2020-06-27 08:09:27 +08:00 committed by GitHub
commit 1fb57ebab0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
25 changed files with 309 additions and 126 deletions

View File

@ -27,9 +27,9 @@ import (
"v2ray.com/core/transport/internet" "v2ray.com/core/transport/internet"
) )
// DoHNameServer implimented DNS over HTTPS (RFC8484) Wire Format, // DoHNameServer implemented DNS over HTTPS (RFC8484) Wire Format,
// which is compatiable with traditional dns over udp(RFC1035), // which is compatible with traditional dns over udp(RFC1035),
// thus most of the DOH implimentation is copied from udpns.go // thus most of the DOH implementation is copied from udpns.go
type DoHNameServer struct { type DoHNameServer struct {
sync.RWMutex sync.RWMutex
ips map[string]record ips map[string]record
@ -48,11 +48,11 @@ func NewDoHNameServer(url *url.URL, dispatcher routing.Dispatcher, clientIP net.
newError("DNS: created Remote DOH client for ", url.String()).AtInfo().WriteToLog() newError("DNS: created Remote DOH client for ", url.String()).AtInfo().WriteToLog()
s := baseDOHNameServer(url, "DOH", clientIP) s := baseDOHNameServer(url, "DOH", clientIP)
// Dispatched connection will be closed (interupted) after each request // Dispatched connection will be closed (interrupted) after each request
// This makes DOH inefficient without a keeped-alive connection // This makes DOH inefficient without a keep-alived connection
// See: core/app/proxyman/outbound/handler.go:113 // See: core/app/proxyman/outbound/handler.go:113
// Using mux (https request wrapped in a stream layer) improves the situation. // Using mux (https request wrapped in a stream layer) improves the situation.
// Recommand to use NewDoHLocalNameServer (DOHL:) if v2ray instance is running on // Recommend to use NewDoHLocalNameServer (DOHL:) if v2ray instance is running on
// a normal network eg. the server side of v2ray // a normal network eg. the server side of v2ray
tr := &http.Transport{ tr := &http.Transport{
MaxIdleConns: 30, MaxIdleConns: 30,
@ -191,7 +191,7 @@ func (s *DoHNameServer) updateIP(req *dnsRequest, ipRec *IPRecord) {
updated = true updated = true
} }
} }
newError(s.name, " got answere: ", req.domain, " ", req.reqType, " -> ", ipRec.IP, " ", elapsed).AtInfo().WriteToLog() newError(s.name, " got answer: ", req.domain, " ", req.reqType, " -> ", ipRec.IP, " ", elapsed).AtInfo().WriteToLog()
if updated { if updated {
s.ips[req.domain] = rec s.ips[req.domain] = rec
@ -246,10 +246,14 @@ func (s *DoHNameServer) sendQuery(ctx context.Context, domain string, option IPO
dnsCtx, cancel := context.WithDeadline(dnsCtx, deadline) dnsCtx, cancel := context.WithDeadline(dnsCtx, deadline)
defer cancel() defer cancel()
b, _ := dns.PackMessage(r.msg) b, err := dns.PackMessage(r.msg)
if err != nil {
newError("failed to pack dns query").Base(err).AtError().WriteToLog()
return
}
resp, err := s.dohHTTPSContext(dnsCtx, b.Bytes()) resp, err := s.dohHTTPSContext(dnsCtx, b.Bytes())
if err != nil { if err != nil {
newError("failed to retrive response").Base(err).AtError().WriteToLog() newError("failed to retrieve response").Base(err).AtError().WriteToLog()
return return
} }
rec, err := parseResponse(resp) rec, err := parseResponse(resp)

View File

@ -108,7 +108,7 @@ func (s *ClassicNameServer) HandleResponse(ctx context.Context, packet *udp_prot
ipRec, err := parseResponse(packet.Payload.Bytes()) ipRec, err := parseResponse(packet.Payload.Bytes())
if err != nil { if err != nil {
newError(s.name, " fail to parse responsed DNS udp").AtError().WriteToLog() newError(s.name, " fail to parse responded DNS udp").AtError().WriteToLog()
return return
} }

0
app/proxyman/command/command.go Executable file → Normal file
View File

0
common/crypto/chunk.go Executable file → Normal file
View File

0
common/protocol/account.go Executable file → Normal file
View File

0
common/protocol/context.go Executable file → Normal file
View File

0
common/protocol/id.go Executable file → Normal file
View File

0
common/signal/done/done.go Executable file → Normal file
View File

0
common/signal/notifier.go Executable file → Normal file
View File

0
common/uuid/uuid.go Executable file → Normal file
View File

0
config.go Executable file → Normal file
View File

0
core.go Executable file → Normal file
View File

View File

@ -3,10 +3,15 @@
package http package http
import ( import (
"bufio"
"context" "context"
"encoding/base64" "encoding/base64"
"io" "io"
"strings" "net/http"
"net/url"
"sync"
"golang.org/x/net/http2"
"v2ray.com/core" "v2ray.com/core"
"v2ray.com/core/common" "v2ray.com/core/common"
@ -20,6 +25,7 @@ import (
"v2ray.com/core/features/policy" "v2ray.com/core/features/policy"
"v2ray.com/core/transport" "v2ray.com/core/transport"
"v2ray.com/core/transport/internet" "v2ray.com/core/transport/internet"
"v2ray.com/core/transport/internet/tls"
) )
type Client struct { type Client struct {
@ -27,6 +33,16 @@ type Client struct {
policyManager policy.Manager policyManager policy.Manager
} }
type h2Conn struct {
rawConn net.Conn
h2Conn *http2.ClientConn
}
var (
cachedH2Mutex sync.Mutex
cachedH2Conns map[net.Destination]h2Conn
)
// NewClient create a new http client based on the given config. // NewClient create a new http client based on the given config.
func NewClient(ctx context.Context, config *ClientConfig) (*Client, error) { func NewClient(ctx context.Context, config *ClientConfig) (*Client, error) {
serverList := protocol.NewServerList() serverList := protocol.NewServerList()
@ -54,25 +70,26 @@ func (c *Client) Process(ctx context.Context, link *transport.Link, dialer inter
if outbound == nil || !outbound.Target.IsValid() { if outbound == nil || !outbound.Target.IsValid() {
return newError("target not specified.") return newError("target not specified.")
} }
destination := outbound.Target target := outbound.Target
if destination.Network == net.Network_UDP { if target.Network == net.Network_UDP {
return newError("UDP is not supported by HTTP outbound") return newError("UDP is not supported by HTTP outbound")
} }
var server *protocol.ServerSpec var user *protocol.MemoryUser
var conn internet.Connection var conn internet.Connection
if err := retry.ExponentialBackoff(5, 100).On(func() error { if err := retry.ExponentialBackoff(5, 100).On(func() error {
server = c.serverPicker.PickServer() server := c.serverPicker.PickServer()
dest := server.Destination() dest := server.Destination()
rawConn, err := dialer.Dial(ctx, dest) user = server.PickUser()
if err != nil { targetAddr := target.NetAddr()
return err
}
conn = rawConn
return nil netConn, err := setUpHttpTunnel(ctx, dest, targetAddr, user, dialer)
if netConn != nil {
conn = internet.Connection(netConn)
}
return err
}); err != nil { }); err != nil {
return newError("failed to find an available destination").Base(err) return newError("failed to find an available destination").Base(err)
} }
@ -84,16 +101,10 @@ func (c *Client) Process(ctx context.Context, link *transport.Link, dialer inter
}() }()
p := c.policyManager.ForLevel(0) p := c.policyManager.ForLevel(0)
user := server.PickUser()
if user != nil { if user != nil {
p = c.policyManager.ForLevel(user.Level) p = c.policyManager.ForLevel(user.Level)
} }
if err := setUpHttpTunnel(conn, conn, &destination, user); err != nil {
return err
}
ctx, cancel := context.WithCancel(ctx) ctx, cancel := context.WithCancel(ctx)
timer := signal.CancelAfterInactivity(ctx, cancel, p.Timeouts.ConnectionIdle) timer := signal.CancelAfterInactivity(ctx, cancel, p.Timeouts.ConnectionIdle)
@ -115,30 +126,164 @@ func (c *Client) Process(ctx context.Context, link *transport.Link, dialer inter
} }
// setUpHttpTunnel will create a socket tunnel via HTTP CONNECT method // setUpHttpTunnel will create a socket tunnel via HTTP CONNECT method
func setUpHttpTunnel(reader io.Reader, writer io.Writer, destination *net.Destination, user *protocol.MemoryUser) error { func setUpHttpTunnel(ctx context.Context, dest net.Destination, target string, user *protocol.MemoryUser, dialer internet.Dialer) (net.Conn, error) {
var headers []string req := (&http.Request{
destNetAddr := destination.NetAddr() Method: "CONNECT",
headers = append(headers, "CONNECT "+destNetAddr+" HTTP/1.1") URL: &url.URL{Host: target},
headers = append(headers, "Host: "+destNetAddr) Header: make(http.Header),
Host: target,
}).WithContext(ctx)
if user != nil && user.Account != nil { if user != nil && user.Account != nil {
account := user.Account.(*Account) account := user.Account.(*Account)
auth := account.GetUsername() + ":" + account.GetPassword() auth := account.GetUsername() + ":" + account.GetPassword()
headers = append(headers, "Proxy-Authorization: Basic "+base64.StdEncoding.EncodeToString([]byte(auth))) req.Header.Set("Proxy-Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte(auth)))
} }
headers = append(headers, "Proxy-Connection: Keep-Alive") req.Header.Set("Proxy-Connection", "Keep-Alive")
b := buf.New() connectHttp1 := func(rawConn net.Conn) (net.Conn, error) {
b.WriteString(strings.Join(headers, "\r\n") + "\r\n\r\n") req.Proto = "HTTP/1.1"
if err := buf.WriteAllBytes(writer, b.Bytes()); err != nil { req.ProtoMajor = 1
return err req.ProtoMinor = 1
err := req.Write(rawConn)
if err != nil {
rawConn.Close()
return nil, err
}
resp, err := http.ReadResponse(bufio.NewReader(rawConn), req)
if err != nil {
rawConn.Close()
return nil, err
}
if resp.StatusCode != http.StatusOK {
rawConn.Close()
return nil, newError("Proxy responded with non 200 code: " + resp.Status)
}
return rawConn, nil
} }
b.Clear() connectHttp2 := func(rawConn net.Conn, h2clientConn *http2.ClientConn) (net.Conn, error) {
if _, err := b.ReadFrom(reader); err != nil { req.Proto = "HTTP/2.0"
return err req.ProtoMajor = 2
req.ProtoMinor = 0
pr, pw := io.Pipe()
req.Body = pr
resp, err := h2clientConn.RoundTrip(req)
if err != nil {
rawConn.Close()
return nil, err
}
if resp.StatusCode != http.StatusOK {
rawConn.Close()
return nil, newError("Proxy responded with non 200 code: " + resp.Status)
}
return newHttp2Conn(rawConn, pw, resp.Body), nil
} }
return nil cachedH2Mutex.Lock()
defer cachedH2Mutex.Unlock()
if cachedConn, found := cachedH2Conns[dest]; found {
if cachedConn.rawConn != nil && cachedConn.h2Conn != nil {
rc := cachedConn.rawConn
cc := cachedConn.h2Conn
if cc.CanTakeNewRequest() {
proxyConn, err := connectHttp2(rc, cc)
if err != nil {
return nil, err
}
return proxyConn, nil
}
}
}
rawConn, err := dialer.Dial(ctx, dest)
if err != nil {
return nil, err
}
nextProto := ""
if tlsConn, ok := rawConn.(*tls.Conn); ok {
if err := tlsConn.Handshake(); err != nil {
rawConn.Close()
return nil, err
}
nextProto = tlsConn.ConnectionState().NegotiatedProtocol
}
switch nextProto {
case "":
fallthrough
case "http/1.1":
return connectHttp1(rawConn)
case "h2":
t := http2.Transport{}
h2clientConn, err := t.NewClientConn(rawConn)
if err != nil {
rawConn.Close()
return nil, err
}
proxyConn, err := connectHttp2(rawConn, h2clientConn)
if err != nil {
rawConn.Close()
return nil, err
}
if cachedH2Conns == nil {
cachedH2Conns = make(map[net.Destination]h2Conn)
}
cachedH2Conns[dest] = h2Conn{
rawConn: rawConn,
h2Conn: h2clientConn,
}
return proxyConn, err
default:
return nil, newError("negotiated unsupported application layer protocol: " + nextProto)
}
}
func newHttp2Conn(c net.Conn, pipedReqBody *io.PipeWriter, respBody io.ReadCloser) net.Conn {
return &http2Conn{Conn: c, in: pipedReqBody, out: respBody}
}
type http2Conn struct {
net.Conn
in *io.PipeWriter
out io.ReadCloser
}
func (h *http2Conn) Read(p []byte) (n int, err error) {
return h.out.Read(p)
}
func (h *http2Conn) Write(p []byte) (n int, err error) {
return h.in.Write(p)
}
func (h *http2Conn) Close() error {
h.in.Close()
return h.out.Close()
}
func (h *http2Conn) CloseConn() error {
return h.Conn.Close()
}
func (h *http2Conn) CloseWrite() error {
return h.in.Close()
}
func (h *http2Conn) CloseRead() error {
return h.out.Close()
} }
func init() { func init() {

0
proxy/http/server.go Executable file → Normal file
View File

0
proxy/proxy.go Executable file → Normal file
View File

View File

@ -8,7 +8,7 @@ import (
"v2ray.com/core/common/uuid" "v2ray.com/core/common/uuid"
) )
// MemoryAccount is an in-memory from of VMess account. // MemoryAccount is an in-memory form of VMess account.
type MemoryAccount struct { type MemoryAccount struct {
// ID is the main ID of the account. // ID is the main ID of the account.
ID *protocol.ID ID *protocol.ID

0
proxy/vmess/account.pb.go Executable file → Normal file
View File

0
proxy/vmess/account.proto Executable file → Normal file
View File

View File

@ -12,10 +12,10 @@ const KDFSaltConst_AEADRespHeaderPayloadIV = "AEAD Resp Header IV"
const KDFSaltConst_VMessAEADKDF = "VMess AEAD KDF" const KDFSaltConst_VMessAEADKDF = "VMess AEAD KDF"
const KDFSaltConst_VmessAuthIDCheckValue = "VMess AuthID Check Value"
const KDFSaltConst_VMessLengthMask = "VMess AuthID Mask Value"
const KDFSaltConst_VMessHeaderPayloadAEADKey = "VMess Header AEAD Key" const KDFSaltConst_VMessHeaderPayloadAEADKey = "VMess Header AEAD Key"
const KDFSaltConst_VMessHeaderPayloadAEADIV = "VMess Header AEAD Nonce" const KDFSaltConst_VMessHeaderPayloadAEADIV = "VMess Header AEAD Nonce"
const KDFSaltConst_VMessHeaderPayloadLengthAEADKey = "VMess Header AEAD Key_Length"
const KDFSaltConst_VMessHeaderPayloadLengthAEADIV = "VMess Header AEAD Nonce_Length"

View File

@ -4,10 +4,8 @@ import (
"bytes" "bytes"
"crypto/aes" "crypto/aes"
"crypto/cipher" "crypto/cipher"
"crypto/hmac"
"crypto/rand" "crypto/rand"
"encoding/binary" "encoding/binary"
"errors"
"io" "io"
"time" "time"
"v2ray.com/core/common" "v2ray.com/core/common"
@ -28,39 +26,54 @@ func SealVMessAEADHeader(key [16]byte, data []byte) []byte {
common.Must(binary.Write(aeadPayloadLengthSerializeBuffer, binary.BigEndian, headerPayloadDataLen)) common.Must(binary.Write(aeadPayloadLengthSerializeBuffer, binary.BigEndian, headerPayloadDataLen))
authidCheckValue := KDF16(key[:], KDFSaltConst_VmessAuthIDCheckValue, string(generatedAuthID[:]), string(aeadPayloadLengthSerializeBuffer.Bytes()), string(connectionNonce))
aeadPayloadLengthSerializedByte := aeadPayloadLengthSerializeBuffer.Bytes() aeadPayloadLengthSerializedByte := aeadPayloadLengthSerializeBuffer.Bytes()
var payloadHeaderLengthAEADEncrypted []byte
aeadPayloadLengthMask := KDF16(key[:], KDFSaltConst_VMessLengthMask, string(generatedAuthID[:]), string(connectionNonce[:]))[:2] {
payloadHeaderLengthAEADKey := KDF16(key[:], KDFSaltConst_VMessHeaderPayloadLengthAEADKey, string(generatedAuthID[:]), string(connectionNonce))
aeadPayloadLengthSerializedByte[0] = aeadPayloadLengthSerializedByte[0] ^ aeadPayloadLengthMask[0] payloadHeaderLengthAEADNonce := KDF(key[:], KDFSaltConst_VMessHeaderPayloadLengthAEADIV, string(generatedAuthID[:]), string(connectionNonce))[:12]
aeadPayloadLengthSerializedByte[1] = aeadPayloadLengthSerializedByte[1] ^ aeadPayloadLengthMask[1]
payloadHeaderAEADKey := KDF16(key[:], KDFSaltConst_VMessHeaderPayloadAEADKey, string(generatedAuthID[:]), string(connectionNonce)) payloadHeaderLengthAEADAESBlock, err := aes.NewCipher(payloadHeaderLengthAEADKey)
if err != nil {
panic(err.Error())
}
payloadHeaderAEADNonce := KDF(key[:], KDFSaltConst_VMessHeaderPayloadAEADIV, string(generatedAuthID[:]), string(connectionNonce))[:12] payloadHeaderAEAD, err := cipher.NewGCM(payloadHeaderLengthAEADAESBlock)
payloadHeaderAEADAESBlock, err := aes.NewCipher(payloadHeaderAEADKey) if err != nil {
if err != nil { panic(err.Error())
panic(err.Error()) }
payloadHeaderLengthAEADEncrypted = payloadHeaderAEAD.Seal(nil, payloadHeaderLengthAEADNonce, aeadPayloadLengthSerializedByte, generatedAuthID[:])
} }
payloadHeaderAEAD, err := cipher.NewGCM(payloadHeaderAEADAESBlock) var payloadHeaderAEADEncrypted []byte
if err != nil { {
panic(err.Error()) payloadHeaderAEADKey := KDF16(key[:], KDFSaltConst_VMessHeaderPayloadAEADKey, string(generatedAuthID[:]), string(connectionNonce))
payloadHeaderAEADNonce := KDF(key[:], KDFSaltConst_VMessHeaderPayloadAEADIV, string(generatedAuthID[:]), string(connectionNonce))[:12]
payloadHeaderAEADAESBlock, err := aes.NewCipher(payloadHeaderAEADKey)
if err != nil {
panic(err.Error())
}
payloadHeaderAEAD, err := cipher.NewGCM(payloadHeaderAEADAESBlock)
if err != nil {
panic(err.Error())
}
payloadHeaderAEADEncrypted = payloadHeaderAEAD.Seal(nil, payloadHeaderAEADNonce, data, generatedAuthID[:])
} }
payloadHeaderAEADEncrypted := payloadHeaderAEAD.Seal(nil, payloadHeaderAEADNonce, data, generatedAuthID[:])
var outputBuffer = bytes.NewBuffer(nil) var outputBuffer = bytes.NewBuffer(nil)
common.Must2(outputBuffer.Write(generatedAuthID[:])) //16 common.Must2(outputBuffer.Write(generatedAuthID[:])) //16
common.Must2(outputBuffer.Write(authidCheckValue)) //16 common.Must2(outputBuffer.Write(payloadHeaderLengthAEADEncrypted)) //2+16
common.Must2(outputBuffer.Write(aeadPayloadLengthSerializedByte)) //2
common.Must2(outputBuffer.Write(connectionNonce)) //8 common.Must2(outputBuffer.Write(connectionNonce)) //8
@ -70,72 +83,93 @@ func SealVMessAEADHeader(key [16]byte, data []byte) []byte {
} }
func OpenVMessAEADHeader(key [16]byte, authid [16]byte, data io.Reader) ([]byte, bool, error, int) { func OpenVMessAEADHeader(key [16]byte, authid [16]byte, data io.Reader) ([]byte, bool, error, int) {
var authidCheckValue [16]byte var payloadHeaderLengthAEADEncrypted [18]byte
var headerPayloadDataLen [2]byte
var nonce [8]byte var nonce [8]byte
authidCheckValueReadBytesCounts, err := io.ReadFull(data, authidCheckValue[:]) var bytesRead int
if err != nil {
return nil, false, err, authidCheckValueReadBytesCounts
}
headerPayloadDataLenReadBytesCounts, err := io.ReadFull(data, headerPayloadDataLen[:]) authidCheckValueReadBytesCounts, err := io.ReadFull(data, payloadHeaderLengthAEADEncrypted[:])
bytesRead += authidCheckValueReadBytesCounts
if err != nil { if err != nil {
return nil, false, err, authidCheckValueReadBytesCounts + headerPayloadDataLenReadBytesCounts return nil, false, err, bytesRead
} }
nonceReadBytesCounts, err := io.ReadFull(data, nonce[:]) nonceReadBytesCounts, err := io.ReadFull(data, nonce[:])
bytesRead += nonceReadBytesCounts
if err != nil { if err != nil {
return nil, false, err, authidCheckValueReadBytesCounts + headerPayloadDataLenReadBytesCounts + nonceReadBytesCounts return nil, false, err, bytesRead
} }
//Unmask Length //Decrypt Length
LengthMask := KDF16(key[:], KDFSaltConst_VMessLengthMask, string(authid[:]), string(nonce[:]))[:2] var decryptedAEADHeaderLengthPayloadResult []byte
headerPayloadDataLen[0] = headerPayloadDataLen[0] ^ LengthMask[0] {
headerPayloadDataLen[1] = headerPayloadDataLen[1] ^ LengthMask[1] payloadHeaderLengthAEADKey := KDF16(key[:], KDFSaltConst_VMessHeaderPayloadLengthAEADKey, string(authid[:]), string(nonce[:]))
authidCheckValueReceivedFromNetwork := KDF16(key[:], KDFSaltConst_VmessAuthIDCheckValue, string(authid[:]), string(headerPayloadDataLen[:]), string(nonce[:])) payloadHeaderLengthAEADNonce := KDF(key[:], KDFSaltConst_VMessHeaderPayloadLengthAEADIV, string(authid[:]), string(nonce[:]))[:12]
if !hmac.Equal(authidCheckValueReceivedFromNetwork, authidCheckValue[:]) { payloadHeaderAEADAESBlock, err := aes.NewCipher(payloadHeaderLengthAEADKey)
return nil, true, errCheckMismatch, authidCheckValueReadBytesCounts + headerPayloadDataLenReadBytesCounts + nonceReadBytesCounts if err != nil {
panic(err.Error())
}
payloadHeaderLengthAEAD, err := cipher.NewGCM(payloadHeaderAEADAESBlock)
if err != nil {
panic(err.Error())
}
decryptedAEADHeaderLengthPayload, erropenAEAD := payloadHeaderLengthAEAD.Open(nil, payloadHeaderLengthAEADNonce, payloadHeaderLengthAEADEncrypted[:], authid[:])
if erropenAEAD != nil {
return nil, true, erropenAEAD, bytesRead
}
decryptedAEADHeaderLengthPayloadResult = decryptedAEADHeaderLengthPayload
} }
var length uint16 var length uint16
common.Must(binary.Read(bytes.NewReader(headerPayloadDataLen[:]), binary.BigEndian, &length)) common.Must(binary.Read(bytes.NewReader(decryptedAEADHeaderLengthPayloadResult[:]), binary.BigEndian, &length))
payloadHeaderAEADKey := KDF16(key[:], KDFSaltConst_VMessHeaderPayloadAEADKey, string(authid[:]), string(nonce[:])) var decryptedAEADHeaderPayloadR []byte
payloadHeaderAEADNonce := KDF(key[:], KDFSaltConst_VMessHeaderPayloadAEADIV, string(authid[:]), string(nonce[:]))[:12] var payloadHeaderAEADEncryptedReadedBytesCounts int
//16 == AEAD Tag size {
payloadHeaderAEADEncrypted := make([]byte, length+16) payloadHeaderAEADKey := KDF16(key[:], KDFSaltConst_VMessHeaderPayloadAEADKey, string(authid[:]), string(nonce[:]))
payloadHeaderAEADEncryptedReadedBytesCounts, err := io.ReadFull(data, payloadHeaderAEADEncrypted) payloadHeaderAEADNonce := KDF(key[:], KDFSaltConst_VMessHeaderPayloadAEADIV, string(authid[:]), string(nonce[:]))[:12]
if err != nil {
return nil, false, err, authidCheckValueReadBytesCounts + headerPayloadDataLenReadBytesCounts + payloadHeaderAEADEncryptedReadedBytesCounts + nonceReadBytesCounts //16 == AEAD Tag size
payloadHeaderAEADEncrypted := make([]byte, length+16)
payloadHeaderAEADEncryptedReadedBytesCounts, err = io.ReadFull(data, payloadHeaderAEADEncrypted)
bytesRead += payloadHeaderAEADEncryptedReadedBytesCounts
if err != nil {
return nil, false, err, bytesRead
}
payloadHeaderAEADAESBlock, err := aes.NewCipher(payloadHeaderAEADKey)
if err != nil {
panic(err.Error())
}
payloadHeaderAEAD, err := cipher.NewGCM(payloadHeaderAEADAESBlock)
if err != nil {
panic(err.Error())
}
decryptedAEADHeaderPayload, erropenAEAD := payloadHeaderAEAD.Open(nil, payloadHeaderAEADNonce, payloadHeaderAEADEncrypted, authid[:])
if erropenAEAD != nil {
return nil, true, erropenAEAD, bytesRead
}
decryptedAEADHeaderPayloadR = decryptedAEADHeaderPayload
} }
payloadHeaderAEADAESBlock, err := aes.NewCipher(payloadHeaderAEADKey) return decryptedAEADHeaderPayloadR, false, nil, bytesRead
if err != nil {
panic(err.Error())
}
payloadHeaderAEAD, err := cipher.NewGCM(payloadHeaderAEADAESBlock)
if err != nil {
panic(err.Error())
}
decryptedAEADHeaderPayload, erropenAEAD := payloadHeaderAEAD.Open(nil, payloadHeaderAEADNonce, payloadHeaderAEADEncrypted, authid[:])
if erropenAEAD != nil {
return nil, true, erropenAEAD, authidCheckValueReadBytesCounts + headerPayloadDataLenReadBytesCounts + payloadHeaderAEADEncryptedReadedBytesCounts + nonceReadBytesCounts
}
return decryptedAEADHeaderPayload, false, nil, authidCheckValueReadBytesCounts + headerPayloadDataLenReadBytesCounts + payloadHeaderAEADEncryptedReadedBytesCounts + nonceReadBytesCounts
} }
var errCheckMismatch = errors.New("check verify failed")

0
transport/internet/kcp/segment.go Executable file → Normal file
View File

View File

@ -15,10 +15,10 @@ var (
type controller func(network, address string, fd uintptr) error type controller func(network, address string, fd uintptr) error
type DefaultListener struct { type DefaultListener struct {
contollers []controller controllers []controller
} }
func getControlFunc(ctx context.Context, sockopt *SocketConfig, contollers []controller) func(network, address string, c syscall.RawConn) error { func getControlFunc(ctx context.Context, sockopt *SocketConfig, controllers []controller) func(network, address string, c syscall.RawConn) error {
return func(network, address string, c syscall.RawConn) error { return func(network, address string, c syscall.RawConn) error {
return c.Control(func(fd uintptr) { return c.Control(func(fd uintptr) {
if sockopt != nil { if sockopt != nil {
@ -27,7 +27,7 @@ func getControlFunc(ctx context.Context, sockopt *SocketConfig, contollers []con
} }
} }
for _, controller := range contollers { for _, controller := range controllers {
if err := controller(network, address, fd); err != nil { if err := controller(network, address, fd); err != nil {
newError("failed to apply external controller").Base(err).WriteToLog(session.ExportIDToError(ctx)) newError("failed to apply external controller").Base(err).WriteToLog(session.ExportIDToError(ctx))
} }
@ -39,8 +39,8 @@ func getControlFunc(ctx context.Context, sockopt *SocketConfig, contollers []con
func (dl *DefaultListener) Listen(ctx context.Context, addr net.Addr, sockopt *SocketConfig) (net.Listener, error) { func (dl *DefaultListener) Listen(ctx context.Context, addr net.Addr, sockopt *SocketConfig) (net.Listener, error) {
var lc net.ListenConfig var lc net.ListenConfig
if sockopt != nil || len(dl.contollers) > 0 { if sockopt != nil || len(dl.controllers) > 0 {
lc.Control = getControlFunc(ctx, sockopt, dl.contollers) lc.Control = getControlFunc(ctx, sockopt, dl.controllers)
} }
return lc.Listen(ctx, addr.Network(), addr.String()) return lc.Listen(ctx, addr.Network(), addr.String())
@ -49,8 +49,8 @@ func (dl *DefaultListener) Listen(ctx context.Context, addr net.Addr, sockopt *S
func (dl *DefaultListener) ListenPacket(ctx context.Context, addr net.Addr, sockopt *SocketConfig) (net.PacketConn, error) { func (dl *DefaultListener) ListenPacket(ctx context.Context, addr net.Addr, sockopt *SocketConfig) (net.PacketConn, error) {
var lc net.ListenConfig var lc net.ListenConfig
if sockopt != nil || len(dl.contollers) > 0 { if sockopt != nil || len(dl.controllers) > 0 {
lc.Control = getControlFunc(ctx, sockopt, dl.contollers) lc.Control = getControlFunc(ctx, sockopt, dl.controllers)
} }
return lc.ListenPacket(ctx, addr.Network(), addr.String()) return lc.ListenPacket(ctx, addr.Network(), addr.String())
@ -65,6 +65,6 @@ func RegisterListenerController(controller func(network, address string, fd uint
return newError("nil listener controller") return newError("nil listener controller")
} }
effectiveListener.contollers = append(effectiveListener.contollers, controller) effectiveListener.controllers = append(effectiveListener.controllers, controller)
return nil return nil
} }

View File

@ -14,25 +14,25 @@ import (
//go:generate errorgen //go:generate errorgen
var ( var (
_ buf.Writer = (*conn)(nil) _ buf.Writer = (*Conn)(nil)
) )
type conn struct { type Conn struct {
*tls.Conn *tls.Conn
} }
func (c *conn) WriteMultiBuffer(mb buf.MultiBuffer) error { func (c *Conn) WriteMultiBuffer(mb buf.MultiBuffer) error {
mb = buf.Compact(mb) mb = buf.Compact(mb)
mb, err := buf.WriteMultiBuffer(c, mb) mb, err := buf.WriteMultiBuffer(c, mb)
buf.ReleaseMulti(mb) buf.ReleaseMulti(mb)
return err return err
} }
func (c *conn) HandshakeAddress() net.Address { func (c *Conn) HandshakeAddress() net.Address {
if err := c.Handshake(); err != nil { if err := c.Handshake(); err != nil {
return nil return nil
} }
state := c.Conn.ConnectionState() state := c.ConnectionState()
if state.ServerName == "" { if state.ServerName == "" {
return nil return nil
} }
@ -42,7 +42,7 @@ func (c *conn) HandshakeAddress() net.Address {
// Client initiates a TLS client handshake on the given connection. // Client initiates a TLS client handshake on the given connection.
func Client(c net.Conn, config *tls.Config) net.Conn { func Client(c net.Conn, config *tls.Config) net.Conn {
tlsConn := tls.Client(c, config) tlsConn := tls.Client(c, config)
return &conn{Conn: tlsConn} return &Conn{Conn: tlsConn}
} }
func copyConfig(c *tls.Config) *utls.Config { func copyConfig(c *tls.Config) *utls.Config {
@ -63,5 +63,5 @@ func UClient(c net.Conn, config *tls.Config) net.Conn {
// Server initiates a TLS server handshake on the given connection. // Server initiates a TLS server handshake on the given connection.
func Server(c net.Conn, config *tls.Config) net.Conn { func Server(c net.Conn, config *tls.Config) net.Conn {
tlsConn := tls.Server(c, config) tlsConn := tls.Server(c, config)
return &conn{Conn: tlsConn} return &Conn{Conn: tlsConn}
} }

0
transport/internet/websocket/ws.go Executable file → Normal file
View File

0
v2ray.go Executable file → Normal file
View File