Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
152 changes: 152 additions & 0 deletions guard.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
package reality

import (
"io"
"net"
"sync"
"time"
)

// [REALITY] SECTION: guard the Client Finished

// guardConn is the client's conn while REALITY waits for the Client Finished.
//
// The target has already seen the same Client Hello, so it gets the client's
// bytes too. Only the last byte of each record that REALITY has not finished
// with is held back, so a valid Client Finished never reaches the target. If
// REALITY rejects a record, or the target answers first, REALITY sends nothing
// of its own: the held bytes go to the target and the client gets the
// target's answer, so a replayed Client Hello followed by invalid data cannot
// tell REALITY apart from the target.
type guardConn struct {
net.Conn
target net.Conn

pending []byte // read by REALITY but not yet sent to the target
start int // stream offset of pending[0]
read int // stream offset of the end of what REALITY has read
done int // stream offset of the end of the last complete record REALITY has read

header [recordHeaderLen]byte // of the record being read
headerLen int
recordEnd int // stream offset of the end of the record being read, once its header is complete

mutex sync.Mutex
state int // guardWaiting, guardVerified or guardHandedOver
finished chan struct{} // closed when watch returns
}

const (
guardWaiting = iota
guardVerified
guardHandedOver
)

func newGuardConn(conn, target net.Conn) *guardConn {
return &guardConn{Conn: conn, target: target, finished: make(chan struct{})}
}

func (g *guardConn) Read(b []byte) (int, error) {
g.send(g.done) // REALITY reads again, so it has accepted every complete record it had
n, err := g.Conn.Read(b)
g.pending = append(g.pending, b[:n]...)
hold := -1
for p := b[:n]; len(p) > 0 || g.headerLen == recordHeaderLen && g.read == g.recordEnd; {
if g.headerLen < recordHeaderLen {
c := copy(g.header[g.headerLen:], p)
g.headerLen += c
g.read += c
p = p[c:]
if g.headerLen == recordHeaderLen {
g.recordEnd = g.read + (int(g.header[3])<<8 | int(g.header[4]))
}
continue
}
c := min(g.recordEnd-g.read, len(p))
g.read += c
p = p[c:]
if g.read == g.recordEnd { // a complete record
if hold == -1 {
hold = g.recordEnd - 1 // the first one REALITY has not processed yet
}
g.done = g.recordEnd
g.headerLen = 0
}
}
if hold == -1 {
hold = g.read
}
g.send(hold)
return n, err
}

// Write drops what REALITY sends while it is guarded: only alerts for invalid data, which the target answers instead.
func (g *guardConn) Write(b []byte) (int, error) {
return len(b), nil
}

func (g *guardConn) send(end int) {
if n := end - g.start; n > 0 {
g.target.Write(g.pending[:n])
g.pending = g.pending[n:]
g.start = end
}
}

// watch forwards what the target sends after its handshake flight to the client
// once REALITY has handed the connection over, and hands it over itself if the
// target answers before the Client Finished is verified.
func (g *guardConn) watch(skip int, target net.Conn, client CloseWriteConn) {
defer close(g.finished)
buf := make([]byte, size)
if skip > 0 {
io.ReadFull(g.target, buf[:skip]) // the rest of the target's flight, which REALITY has replaced
}
for {
n, err := target.Read(buf)
g.mutex.Lock()
if g.state == guardVerified {
g.mutex.Unlock()
return
}
if g.state == guardWaiting {
g.state = guardHandedOver
g.Conn.SetReadDeadline(time.Now()) // stop REALITY's read
}
g.mutex.Unlock()
if n > 0 {
client.Write(buf[:n])
}
if err != nil {
client.CloseWrite()
return
}
}
}

// verified reports whether REALITY keeps the connection, after it has read the
// Client Finished with error err. Otherwise the target gets everything the client sent.
func (g *guardConn) verified(err error) bool {
g.mutex.Lock()
if err == nil && g.state == guardWaiting {
g.state = guardVerified
} else {
g.state = guardHandedOver
}
state := g.state
g.mutex.Unlock()
if state == guardVerified {
return true
}
g.Conn.SetReadDeadline(time.Time{})
g.send(g.start + len(g.pending))
return false
}

func (g *guardConn) handedOver() bool {
g.mutex.Lock()
defer g.mutex.Unlock()
return g.state == guardHandedOver
}

// [REALITY] SECTION END
73 changes: 73 additions & 0 deletions guard_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
package reality

import (
"bytes"
"io"
"net"
"testing"
"time"
)

type chunkConn struct {
net.Conn
chunks [][]byte
}

func (c *chunkConn) Read(b []byte) (int, error) {
if len(c.chunks) == 0 {
return 0, io.EOF
}
n := copy(b, c.chunks[0])
c.chunks = c.chunks[1:]
return n, nil
}

func (c *chunkConn) SetReadDeadline(time.Time) error { return nil }

type sinkConn struct {
net.Conn
written bytes.Buffer
}

func (c *sinkConn) Write(b []byte) (int, error) { return c.written.Write(b) }

func TestGuardConnHoldsLastByteOfUnprocessedRecords(t *testing.T) {
ccs := []byte{20, 3, 3, 0, 1, 1}
finished := append([]byte{23, 3, 3, 0, 53}, make([]byte, 53)...)
empty := []byte{23, 3, 3, 0, 0}
stream := append(append(append([]byte{}, ccs...), finished...), empty...)

cases := []struct {
name string
chunks []int // sizes of the client's reads
sent []int // what the target has after each Read returns
}{
// a partial header goes through, then CCS and Finished arrive: hold the CCS's last byte
{"split header", []int{3, 61, 5}, []int{3, 5, 68}},
// one read with everything: hold from the CCS's last byte
{"one read", []int{69}, []int{5}},
// a zero-length record completes with its header, so its last header byte waits
{"zero-length record", []int{64, 4, 1}, []int{5, 68, 68}},
}
for _, c := range cases {
client := &chunkConn{}
for i := 0; i < len(stream); {
n := c.chunks[len(client.chunks)]
client.chunks = append(client.chunks, stream[i:i+n])
i += n
}
target := &sinkConn{}
g := newGuardConn(client, target)
b := make([]byte, 100)
for i, want := range c.sent {
g.Read(b)
if target.written.Len() != want {
t.Errorf("%s: after read %d the target has %d bytes, want %d", c.name, i+1, target.written.Len(), want)
}
}
g.verified(io.ErrUnexpectedEOF) // hand over: the target gets the rest
if !bytes.Equal(target.written.Bytes(), stream) {
t.Errorf("%s: after the hand-over the target has %d bytes, want the whole stream (%d)", c.name, target.written.Len(), len(stream))
}
}
}
37 changes: 21 additions & 16 deletions tls.go
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,7 @@ func Server(ctx context.Context, conn net.Conn, config *Config) (*Conn, error) {
}

copying := false
var guard *guardConn

waitGroup := new(sync.WaitGroup)
waitGroup.Add(2)
Expand Down Expand Up @@ -282,8 +283,9 @@ func Server(ctx context.Context, conn net.Conn, config *Config) (*Conn, error) {
}
break
}
forward := hs.c.conn != conn
mutex.Unlock()
if hs.c.conn != conn {
if forward {
if config.Show && hs.clientHello != nil {
fmt.Printf("REALITY remoteAddr: %v\tforwarded SNI: %v\n", remoteAddr, hs.clientHello.serverName)
}
Expand Down Expand Up @@ -379,32 +381,26 @@ func Server(ctx context.Context, conn net.Conn, config *Config) (*Conn, error) {
s2cSaved = s2cSaved[handshakeLen:]
handshakeLen = 0
}
start := time.Now()
err = hs.handshake()
if config.Show {
fmt.Printf("REALITY remoteAddr: %v\ths.handshake() err: %v\n", remoteAddr, err)
}
if err != nil {
break
}
go func() { // TODO: Probe some time-outs in advance.
if handshakeLen-len(s2cSaved) > 0 {
io.ReadFull(target, buf[:handshakeLen-len(s2cSaved)])
}
if n, err := target.Read(buf); !hs.c.isHandshakeComplete.Load() {
if err != nil {
conn.Close()
}
if config.Show {
fmt.Printf("REALITY remoteAddr: %v\ttime.Since(start): %v\tn: %v\terr: %v\n", remoteAddr, time.Since(start), n, err)
}
}
}()
// until the Client Finished is verified, the target answers anything else (see guardConn)
guard = newGuardConn(conn, target)
go guard.watch(handshakeLen-len(s2cSaved), NewRatelimitedConn(target, &config.LimitFallbackDownload), underlying)
hs.c.conn = guard
err = hs.readClientFinished()
hs.c.conn = conn
if config.Show {
fmt.Printf("REALITY remoteAddr: %v\ths.readClientFinished() err: %v\n", remoteAddr, err)
}
if err != nil {
if !guard.verified(err) {
if config.Show {
fmt.Printf("REALITY remoteAddr: %v\thanded over to the target before the Client Finished\n", remoteAddr)
}
break
}
for {
Expand Down Expand Up @@ -445,6 +441,13 @@ func Server(ctx context.Context, conn net.Conn, config *Config) (*Conn, error) {
break
}
mutex.Unlock()
if guard != nil && guard.handedOver() {
io.Copy(target, NewRatelimitedConn(underlying, &config.LimitFallbackUpload))
if targetWriterCloser, ok := target.(CloseWriteConn); ok {
targetWriterCloser.CloseWrite()
}
<-guard.finished
}
if hs.c.out.handshakeLen[0] == 0 { // if the target sent an incorrect Server Hello, or before that
if hs.c.conn == conn { // if we processed the Client Hello successfully but the target did not
waitGroup.Add(1)
Expand Down Expand Up @@ -482,6 +485,8 @@ func Server(ctx context.Context, conn net.Conn, config *Config) (*Conn, error) {
failureReason = fmt.Sprintf("server name mismatch: %s", hs.clientHello.serverName)
} else if hs.c.conn != conn {
failureReason = "authentication failed or validation criteria not met"
} else if guard != nil && guard.handedOver() {
failureReason = "handed over to the target before the client finished"
} else if hs.c.out.handshakeLen[0] == 0 {
failureReason = "target sent incorrect server hello or handshake incomplete"
} else {
Expand Down