Cloak/internal/multiplex/session.go

351 lines
9.8 KiB
Go
Raw Normal View History

2018-10-05 22:44:20 +00:00
package multiplex
import (
2018-10-23 19:47:58 +00:00
"errors"
2019-08-16 22:47:15 +00:00
"fmt"
2020-04-14 00:53:28 +00:00
"github.com/cbeuw/Cloak/internal/common"
2018-10-05 22:44:20 +00:00
"net"
"sync"
2018-10-23 19:47:58 +00:00
"sync/atomic"
"time"
2019-08-05 13:33:20 +00:00
log "github.com/sirupsen/logrus"
2018-10-05 22:44:20 +00:00
)
const (
acceptBacklog = 1024
defaultInactivityTimeout = 30 * time.Second
defaultMaxOnWireSize = 1<<14 + 256 // https://tools.ietf.org/html/rfc8446#section-5.2
2018-10-05 22:44:20 +00:00
)
2018-10-27 14:27:43 +00:00
var ErrBrokenSession = errors.New("broken session")
var errRepeatSessionClosing = errors.New("trying to close a closed session")
var errRepeatStreamClosing = errors.New("trying to close a closed stream")
2020-10-15 20:32:38 +00:00
var errNoMultiplex = errors.New("a singleplexing session can have only one stream")
2018-10-27 14:27:43 +00:00
2019-08-11 23:22:15 +00:00
type SessionConfig struct {
2020-04-10 15:09:05 +00:00
Obfuscator
2018-10-05 22:44:20 +00:00
2020-10-20 23:54:36 +00:00
// Valve is used to limit transmission rates, and record and limit usage
2019-08-11 23:22:15 +00:00
Valve
Unordered bool
2020-10-20 23:54:36 +00:00
// A Singleplexing session always has just one stream
2020-10-15 20:32:38 +00:00
Singleplex bool
2020-10-18 13:42:47 +00:00
// maximum size of an obfuscated frame, including headers and overhead
MsgOnWireSizeLimit int
// InactivityTimeout sets the duration a Session waits while it has no active streams before it closes itself
InactivityTimeout time.Duration
2019-08-11 23:22:15 +00:00
}
2020-10-21 15:37:32 +00:00
// A Session represents a self-contained communication chain between local and remote. It manages its streams,
// controls serialisation and encryption of data sent and received using the supplied Obfuscator, and send and receive
// data through a manged connection pool filled with underlying connections added to it.
2019-08-11 23:22:15 +00:00
type Session struct {
id uint32
SessionConfig
2019-08-02 00:01:19 +00:00
2018-10-27 22:35:46 +00:00
// atomic
2018-10-23 19:47:58 +00:00
nextStreamID uint32
2018-10-05 22:44:20 +00:00
// atomic
activeStreamCount uint32
streamsM sync.Mutex
streams map[uint32]*Stream
// For accepting new streams
acceptCh chan *Stream
2018-10-05 22:44:20 +00:00
// a pool of heap allocated frame objects so we don't have to allocate a new one each time we receive a frame
recvFramePool sync.Pool
2020-12-24 11:35:29 +00:00
streamObfsBufPool sync.Pool
2018-10-05 22:44:20 +00:00
// Switchboard manages all connections to remote
sb *switchboard
2019-10-08 22:11:16 +00:00
// Used for LocalAddr() and RemoteAddr() etc.
addrs atomic.Value
2019-07-28 22:27:59 +00:00
closed uint32
terminalMsgSetter sync.Once
terminalMsg string
// the max size passed to Write calls before it splits it into multiple frames
2020-10-18 13:42:47 +00:00
// i.e. the max size a piece of data can fit into a Frame.Payload
maxStreamUnitWrite int
// streamSendBufferSize sets the buffer size used to send data from a Stream (Stream.obfsBuf)
streamSendBufferSize int
// connReceiveBufferSize sets the buffer size used to receive data from an underlying Conn (allocated in
// switchboard.deplex)
connReceiveBufferSize int
2018-10-05 22:44:20 +00:00
}
func MakeSession(id uint32, config SessionConfig) *Session {
2018-10-05 22:44:20 +00:00
sesh := &Session{
2019-08-11 23:22:15 +00:00
id: id,
SessionConfig: config,
nextStreamID: 1,
acceptCh: make(chan *Stream, acceptBacklog),
recvFramePool: sync.Pool{New: func() interface{} { return &Frame{} }},
streams: map[uint32]*Stream{},
2018-10-05 22:44:20 +00:00
}
sesh.addrs.Store([]net.Addr{nil, nil})
2019-08-11 23:22:15 +00:00
if config.Valve == nil {
2020-04-08 14:13:49 +00:00
sesh.Valve = UNLIMITED_VALVE
2019-08-11 23:22:15 +00:00
}
2020-10-18 13:42:47 +00:00
if config.MsgOnWireSizeLimit <= 0 {
sesh.MsgOnWireSizeLimit = defaultMaxOnWireSize
}
if config.InactivityTimeout == 0 {
sesh.InactivityTimeout = defaultInactivityTimeout
}
sesh.maxStreamUnitWrite = sesh.MsgOnWireSizeLimit - frameHeaderLength - sesh.maxOverhead
sesh.streamSendBufferSize = sesh.MsgOnWireSizeLimit
sesh.connReceiveBufferSize = 20480 // for backwards compatibility
2020-12-24 11:35:29 +00:00
sesh.streamObfsBufPool = sync.Pool{New: func() interface{} {
b := make([]byte, sesh.streamSendBufferSize)
2020-12-24 11:35:29 +00:00
return &b
}}
2020-10-18 13:42:47 +00:00
sesh.sb = makeSwitchboard(sesh)
time.AfterFunc(sesh.InactivityTimeout, sesh.checkTimeout)
2018-10-05 22:44:20 +00:00
return sesh
}
2020-12-28 12:15:01 +00:00
func (sesh *Session) GetSessionKey() [32]byte {
return sesh.sessionKey
}
func (sesh *Session) streamCountIncr() uint32 {
return atomic.AddUint32(&sesh.activeStreamCount, 1)
}
func (sesh *Session) streamCountDecr() uint32 {
return atomic.AddUint32(&sesh.activeStreamCount, ^uint32(0))
}
func (sesh *Session) streamCount() uint32 {
return atomic.LoadUint32(&sesh.activeStreamCount)
}
2020-10-20 23:54:36 +00:00
// AddConnection is used to add an underlying connection to the connection pool
2018-10-07 17:09:45 +00:00
func (sesh *Session) AddConnection(conn net.Conn) {
2018-10-28 21:22:38 +00:00
sesh.sb.addConn(conn)
addrs := []net.Addr{conn.LocalAddr(), conn.RemoteAddr()}
sesh.addrs.Store(addrs)
2018-10-07 17:09:45 +00:00
}
2020-10-20 23:54:36 +00:00
// OpenStream is similar to net.Dial. It opens up a new stream
2018-10-05 22:44:20 +00:00
func (sesh *Session) OpenStream() (*Stream, error) {
2019-07-28 22:27:59 +00:00
if sesh.IsClosed() {
2018-11-07 21:16:13 +00:00
return nil, ErrBrokenSession
}
id := atomic.AddUint32(&sesh.nextStreamID, 1) - 1
// Because atomic.AddUint32 returns the value after incrementation
2020-10-15 20:32:38 +00:00
if sesh.Singleplex && id > 1 {
// if there are more than one streams, which shouldn't happen if we are
// singleplexing
return nil, errNoMultiplex
}
2020-04-12 11:51:00 +00:00
stream := makeStream(sesh, id)
sesh.streamsM.Lock()
sesh.streams[id] = stream
sesh.streamsM.Unlock()
sesh.streamCountIncr()
2019-08-06 10:19:47 +00:00
log.Tracef("stream %v of session %v opened", id, sesh.id)
2018-10-05 22:44:20 +00:00
return stream, nil
}
2020-10-20 23:54:36 +00:00
// Accept is similar to net.Listener's Accept(). It blocks and returns an incoming stream
2019-07-23 10:06:49 +00:00
func (sesh *Session) Accept() (net.Conn, error) {
2019-07-28 22:27:59 +00:00
if sesh.IsClosed() {
2018-10-27 14:27:43 +00:00
return nil, ErrBrokenSession
2018-10-23 19:47:58 +00:00
}
2019-07-28 22:27:59 +00:00
stream := <-sesh.acceptCh
if stream == nil {
return nil, ErrBrokenSession
}
2019-08-06 10:19:47 +00:00
log.Tracef("stream %v of session %v accepted", stream.id, sesh.id)
2019-07-28 22:27:59 +00:00
return stream, nil
2018-10-05 22:44:20 +00:00
}
func (sesh *Session) closeStream(s *Stream, active bool) error {
if !atomic.CompareAndSwapUint32(&s.closed, 0, 1) {
return fmt.Errorf("closing stream %v: %w", s.id, errRepeatStreamClosing)
2019-10-15 21:06:11 +00:00
}
2020-12-31 23:53:22 +00:00
_ = s.recvBuf.Close() // recvBuf.Close should not return error
if active {
2020-12-24 11:35:29 +00:00
tmpBuf := sesh.streamObfsBufPool.Get().(*[]byte)
// Notify remote that this stream is closed
2020-12-24 11:35:29 +00:00
common.CryptoRandRead((*tmpBuf)[:1])
padLen := int((*tmpBuf)[0]) + 1
payload := (*tmpBuf)[frameHeaderLength : padLen+frameHeaderLength]
common.CryptoRandRead(payload)
2020-04-11 23:49:49 +00:00
// must be holding s.wirtingM on entry
s.writingFrame.Closing = closingStream
s.writingFrame.Payload = payload
2020-12-24 11:35:29 +00:00
err := s.obfuscateAndSend(*tmpBuf, frameHeaderLength)
sesh.streamObfsBufPool.Put(tmpBuf)
if err != nil {
return err
}
log.Tracef("stream %v actively closed.", s.id)
} else {
log.Tracef("stream %v passively closed", s.id)
}
2020-12-04 22:27:24 +00:00
// We set it as nil to signify that the stream id had existed before.
// If we Delete(s.id) straight away, later on in recvDataFromRemote, it will not be able to tell
// if the frame it received was from a new stream or a dying stream whose frame arrived late
sesh.streamsM.Lock()
sesh.streams[s.id] = nil
sesh.streamsM.Unlock()
if sesh.streamCountDecr() == 0 {
2020-10-15 20:32:38 +00:00
if sesh.Singleplex {
return sesh.Close()
} else {
log.Debugf("session %v has no active stream left", sesh.id)
time.AfterFunc(sesh.InactivityTimeout, sesh.checkTimeout)
2020-10-15 20:32:38 +00:00
}
}
return nil
2018-10-05 22:44:20 +00:00
}
// recvDataFromRemote deobfuscate the frame and read the Closing field. If it is a closing frame, it writes the frame
// to the stream buffer, otherwise it fetches the desired stream instance, or creates and stores one if it's a new
// stream and then writes to the stream buffer
2019-08-16 22:47:15 +00:00
func (sesh *Session) recvDataFromRemote(data []byte) error {
frame := sesh.recvFramePool.Get().(*Frame)
defer sesh.recvFramePool.Put(frame)
err := sesh.deobfuscate(frame, data)
2019-08-05 13:33:20 +00:00
if err != nil {
2019-08-16 22:47:15 +00:00
return fmt.Errorf("Failed to decrypt a frame for session %v: %v", sesh.id, err)
2019-08-05 13:33:20 +00:00
}
2020-10-21 15:42:24 +00:00
if frame.Closing == closingSession {
sesh.SetTerminalMsg("Received a closing notification frame")
return sesh.passiveClose()
}
sesh.streamsM.Lock()
if sesh.IsClosed() {
sesh.streamsM.Unlock()
return ErrBrokenSession
}
existingStream, existing := sesh.streams[frame.StreamID]
if existing {
sesh.streamsM.Unlock()
if existingStream == nil {
// this is when the stream existed before but has since been closed. We do nothing
return nil
2018-11-24 00:55:26 +00:00
}
return existingStream.recvFrame(frame)
} else {
newStream := makeStream(sesh, frame.StreamID)
sesh.streams[frame.StreamID] = newStream
sesh.acceptCh <- newStream
sesh.streamsM.Unlock()
2020-03-15 23:56:45 +00:00
// new stream
sesh.streamCountIncr()
return newStream.recvFrame(frame)
2018-11-24 00:55:26 +00:00
}
}
func (sesh *Session) SetTerminalMsg(msg string) {
sesh.terminalMsgSetter.Do(func() {
sesh.terminalMsg = msg
})
}
func (sesh *Session) TerminalMsg() string {
return sesh.terminalMsg
}
func (sesh *Session) closeSession() error {
if !atomic.CompareAndSwapUint32(&sesh.closed, 0, 1) {
2019-08-19 22:23:41 +00:00
log.Debugf("session %v has already been closed", sesh.id)
return errRepeatSessionClosing
}
sesh.streamsM.Lock()
close(sesh.acceptCh)
for id, stream := range sesh.streams {
if stream != nil && atomic.CompareAndSwapUint32(&stream.closed, 0, 1) {
2020-12-31 23:53:22 +00:00
_ = stream.recvBuf.Close() // will not block
delete(sesh.streams, id)
sesh.streamCountDecr()
}
}
sesh.streamsM.Unlock()
return nil
}
func (sesh *Session) passiveClose() error {
log.Debugf("attempting to passively close session %v", sesh.id)
err := sesh.closeSession()
if err != nil {
return err
}
sesh.sb.closeAll()
2019-08-05 13:33:20 +00:00
log.Debugf("session %v closed gracefully", sesh.id)
2018-10-23 19:47:58 +00:00
return nil
}
func (sesh *Session) Close() error {
log.Debugf("attempting to actively close session %v", sesh.id)
err := sesh.closeSession()
if err != nil {
return err
}
// we send a notice frame telling remote to close the session
buf := sesh.streamObfsBufPool.Get().(*[]byte)
common.CryptoRandRead((*buf)[:1])
padLen := int((*buf)[0]) + 1
payload := (*buf)[frameHeaderLength : padLen+frameHeaderLength]
common.CryptoRandRead(payload)
f := &Frame{
StreamID: 0xffffffff,
Seq: 0,
2020-10-21 15:42:24 +00:00
Closing: closingSession,
Payload: payload,
}
i, err := sesh.obfuscate(f, *buf, frameHeaderLength)
if err != nil {
return err
}
_, err = sesh.sb.send((*buf)[:i], new(net.Conn))
if err != nil {
return err
}
sesh.sb.closeAll()
log.Debugf("session %v closed gracefully", sesh.id)
return nil
2018-10-23 19:47:58 +00:00
}
2019-01-20 12:13:29 +00:00
2019-07-28 22:27:59 +00:00
func (sesh *Session) IsClosed() bool {
return atomic.LoadUint32(&sesh.closed) == 1
2019-01-20 12:13:29 +00:00
}
func (sesh *Session) checkTimeout() {
if sesh.streamCount() == 0 && !sesh.IsClosed() {
sesh.SetTerminalMsg("timeout")
sesh.Close()
}
}
2019-07-23 10:06:49 +00:00
func (sesh *Session) Addr() net.Addr { return sesh.addrs.Load().([]net.Addr)[0] }