summaryrefslogtreecommitdiff
path: root/vendor/0xacab.org/leap/shapeshifter/shapeshifter.go
blob: f201e0702638f4268eaf9ab8ae747cc58efa4f62 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
package shapeshifter

import (
	"encoding/base64"
	"fmt"
	"io"
	"log"
	"net"
	"sync"

	"github.com/OperatorFoundation/obfs4/common/ntor"
	"github.com/OperatorFoundation/shapeshifter-transports/transports/obfs4"
	"golang.org/x/net/proxy"
)

type Logger interface {
	Log(msg string)
}

type ShapeShifter struct {
	Cert      string
	IatMode   int
	Target    string // remote ip:port obfs4 server
	SocksAddr string // -proxylistenaddr in shapeshifter-dispatcher
	Logger    Logger
	ln        net.Listener
	errChan   chan error
}

func (ss *ShapeShifter) Open() error {
	err := ss.checkOptions()
	if err != nil {
		return err
	}

	ss.ln, err = net.Listen("tcp", ss.SocksAddr)
	if err != nil {
		return fmt.Errorf("failed to listen: %s", err.Error())
	}

	go ss.clientAcceptLoop()
	return nil
}

func (ss *ShapeShifter) Close() error {
	if ss.ln != nil {
		return ss.ln.Close()
	}
	if ss.errChan != nil {
		close(ss.errChan)
	}
	return nil
}

func (ss *ShapeShifter) GetErrorChannel() chan error {
	if ss.errChan == nil {
		ss.errChan = make(chan error, 2)
	}
	return ss.errChan
}

func (ss ShapeShifter) clientAcceptLoop() error {
	for {
		conn, err := ss.ln.Accept()
		if err != nil {
			if e, ok := err.(net.Error); ok && !e.Temporary() {
				return err
			}
			ss.sendError("Error accepting connection: %v", err)
			continue
		}
		go ss.clientHandler(conn)
	}
}

func (ss ShapeShifter) clientHandler(conn net.Conn) {
	defer conn.Close()

	dialer := proxy.Direct
	transport, err := obfs4.NewObfs4Client(ss.Cert, ss.IatMode, dialer)
	if err != nil {
		ss.sendError("Can not create an obfs4 client (cert: %s, iat-mode: %d): %v", ss.Cert, ss.IatMode, err)
		return
	}
	remote, err := transport.Dial(ss.Target)
	if err != nil {
		ss.sendError("outgoing connection failed %s: %v", ss.Target, err)
		return
	}
	if remote == nil {
		ss.sendError("outgoing connection failed %s", ss.Target)
		return
	}
	defer remote.Close()

	err = copyLoop(conn, remote)
	if err != nil {
		ss.sendError("%s - closed connection: %v", ss.Target, err)
	} else {
		log.Printf("%s - closed connection", ss.Target)
	}

	return
}

func copyLoop(a net.Conn, b net.Conn) error {
	// Note: b is always the pt connection.  a is the SOCKS/ORPort connection.
	errChan := make(chan error, 2)

	var wg sync.WaitGroup
	wg.Add(2)

	go func() {
		defer wg.Done()
		defer b.Close()
		defer a.Close()
		_, err := io.Copy(b, a)
		errChan <- err
	}()
	go func() {
		defer wg.Done()
		defer a.Close()
		defer b.Close()
		_, err := io.Copy(a, b)
		errChan <- err
	}()

	// Wait for both upstream and downstream to close.  Since one side
	// terminating closes the other, the second error in the channel will be
	// something like EINVAL (though io.Copy() will swallow EOF), so only the
	// first error is returned.
	wg.Wait()
	if len(errChan) > 0 {
		return <-errChan
	}

	return nil
}

func (ss *ShapeShifter) checkOptions() error {
	if ss.SocksAddr == "" {
		ss.SocksAddr = "127.0.0.1:0"
	}
	return isCertValid(ss.Cert)
}

func (ss *ShapeShifter) sendError(format string, a ...interface{}) {
	if ss.Logger != nil {
		ss.Logger.Log(fmt.Sprintf(format, a...))
		return
	}

	if ss.errChan == nil {
		ss.errChan = make(chan error, 2)
	}
	select {
	case ss.errChan <- fmt.Errorf(format, a...):
	default:
		log.Printf(format, a...)
	}
}

func isCertValid(cert string) error {
	// copied from github.com/OperatorFoundation/shapeshifter-transports/transports/obfs4/statefile.go
	const certSuffix = "=="
	const certLength = ntor.NodeIDLength + ntor.PublicKeyLength

	if cert == "" {
		return fmt.Errorf("obfs4 transport missing cert argument")
	}

	decoded, err := base64.StdEncoding.DecodeString(cert + certSuffix)
	if err != nil {
		return fmt.Errorf("failed to decode cert: %s", err)
	}

	if len(decoded) != certLength {
		return fmt.Errorf("cert length %d is invalid", len(decoded))
	}

	return nil
}