-
Notifications
You must be signed in to change notification settings - Fork 41
/
Copy pathproxy_service.go
285 lines (238 loc) · 7.14 KB
/
proxy_service.go
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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
package tcp
import (
"context"
"fmt"
"io"
"net"
"time"
validation "github.com/go-ozzo/ozzo-validation"
"github.com/pkg/errors"
"go.opentelemetry.io/otel/metric"
"github.com/cyberark/secretless-broker/internal"
"github.com/cyberark/secretless-broker/pkg/secretless/log"
"github.com/cyberark/secretless-broker/pkg/secretless/plugin/connector/tcp"
)
const closedConnectionErrString = "use of closed network connection"
func duplexStream(
source io.ReadWriter,
destination io.ReadWriter,
) (sourceErrorChan <-chan error, destinationErrorChan <-chan error) {
_sourceErrorChan := make(chan error)
_destinationErrorChan := make(chan error)
go func() {
_sourceErrorChan <- stream(source, destination)
}()
go func() {
_destinationErrorChan <- stream(destination, source)
}()
sourceErrorChan = _sourceErrorChan
destinationErrorChan = _destinationErrorChan
return
}
func stream(source io.Reader, destination io.Writer) error {
_, err := io.Copy(destination, source)
return err
}
type proxyService struct {
connector tcp.Connector
done bool
listener net.Listener
logger log.Logger
retrieveCredentials internal.CredentialsRetriever
throughputCounter metric.BoundInt64Counter
latencyRecorder metric.BoundInt64ValueRecorder
}
type ReadWriteNotifier struct {
readWriter io.ReadWriter
onWrite func(bytesWritten int, timeToHandoff time.Duration)
onRead func(bytesRead int, timeSpentBlocking time.Duration)
}
// Write implements the io.ReadWriter interface.
func (rwn *ReadWriteNotifier) Write(buffer []byte) (int, error) {
start := time.Now()
n, err := rwn.readWriter.Write(buffer)
if err == nil && rwn.onWrite != nil {
rwn.onWrite(n, time.Now().Sub(start))
}
return n, err
}
// Read implements the io.ReadWriter interface.
func (rwn *ReadWriteNotifier) Read(buffer []byte) (int, error) {
start := time.Now()
n, err := rwn.readWriter.Read(buffer)
if err == nil && rwn.onRead != nil {
rwn.onRead(n, time.Now().Sub(start))
}
return n, err
}
func AddTelemetry(
svc internal.Service,
throughputCounter metric.BoundInt64Counter,
latencyRecorder metric.BoundInt64ValueRecorder,
) {
_svc := svc.(*proxyService)
_svc.throughputCounter = throughputCounter
_svc.latencyRecorder = latencyRecorder
}
// NewProxyService constructs a new instance of a TCP ProxyService. The
// constructor takes a TCP Connector, CredentialResolver and Listener.
// A TCP ProxyService is able to Connect with Credentials then subsequently stream
// bytes between client and target service
func NewProxyService(
connector tcp.Connector,
listener net.Listener,
logger log.Logger,
retrieveCredentials internal.CredentialsRetriever,
) (internal.Service, error) {
errors := validation.Errors{}
if connector == nil {
errors["connector"] = fmt.Errorf("connector cannot be nil")
}
if retrieveCredentials == nil {
errors["retrieveCredentials"] = fmt.Errorf("retrieveCredentials cannot be nil")
}
if listener == nil {
errors["logger"] = fmt.Errorf("logger cannot be nil")
}
if logger == nil {
errors["listener"] = fmt.Errorf("listener cannot be nil")
}
if err := errors.Filter(); err != nil {
return nil, err
}
return &proxyService{
connector: connector,
retrieveCredentials: retrieveCredentials,
listener: listener,
logger: logger,
done: false,
}, nil
}
func closeConn(conn net.Conn, connDescription string, logger log.Logger) {
if conn == nil {
return
}
err := conn.Close()
if err != nil {
logger.Warnf("Failed on closing %s connection: %s", connDescription, err)
}
}
func (proxy *proxyService) handleConnection(clientConn net.Conn) error {
var targetConn net.Conn
logger := proxy.logger
defer func() {
closeConn(clientConn, "client", logger)
closeConn(targetConn, "target", logger)
}()
backendCredentials, err := proxy.retrieveCredentials()
// zeroize credentials if we exit early due to an error
defer internal.ZeroizeCredentials(backendCredentials)
if err != nil {
return errors.Wrap(err, "failed on retrieve credentials")
}
logger.Debugf("New connection on %v.\n", clientConn.LocalAddr())
targetConn, err = proxy.connector.Connect(clientConn, backendCredentials)
if err != nil {
return errors.Wrap(err, "failed on connect")
}
// immediately zeroize credentials after connecting
internal.ZeroizeCredentials(backendCredentials)
logger.Debugf("Proxying connection on %v to %v.\n", clientConn.LocalAddr(), targetConn.RemoteAddr())
var lastTargetRead time.Time
var lastClientRead time.Time
// TODO: concurrency protections
clientErrChan, destErrChan := duplexStream(
&ReadWriteNotifier{
readWriter: clientConn,
onWrite: func(bytesWritten int, timeToHandoff time.Duration) {
// clientWrite
streamLatency := time.Now().Sub(lastTargetRead)
ctx := context.Background()
proxy.throughputCounter.Add(ctx, int64(bytesWritten))
proxy.latencyRecorder.Record(ctx, streamLatency.Microseconds())
},
onRead: func(bytesRead int, timeSpentBlocking time.Duration) {
// clientRead
lastClientRead = time.Now()
},
}, &ReadWriteNotifier{
readWriter: targetConn,
onWrite: func(bytesWritten int, timeToHandoff time.Duration) {
// targetWrite
streamLatency := time.Now().Sub(lastClientRead)
ctx := context.Background()
proxy.throughputCounter.Add(ctx, int64(bytesWritten))
proxy.latencyRecorder.Record(ctx, streamLatency.Microseconds())
},
onRead: func(bytesRead int, timeSpentBlocking time.Duration) {
// targetRead
lastTargetRead = time.Now()
},
},
)
var closer string
select {
case err = <-clientErrChan:
closer = "client"
case err = <-destErrChan:
closer = "target"
}
if err != nil {
return errors.Wrap(
err,
fmt.Sprintf(
`connection on %v failed while streaming from %s connection`,
clientConn.LocalAddr(),
closer,
),
)
}
logger.Debugf("Connection on %v closed by %s.\n", clientConn.LocalAddr(), closer)
return nil
}
// Start initiates the net.Listener to listen for incoming connections
func (proxy *proxyService) Start() error {
logger := proxy.logger
logger.Infof("Starting service")
if proxy.done {
return fmt.Errorf("cannot call Start on stopped ProxyService")
}
go func() { // n go routines for n tcp ProxyServices
for !proxy.done {
// TODO: can accepts happen in parallel ?
conn, err := proxy.listener.Accept()
if opErr, ok := err.(*net.OpError); ok && opErr.Err.Error() == closedConnectionErrString {
logger.Info("Listener closed")
return
}
if err != nil {
logger.Errorf("Failed on accept connection: %s", err)
return
}
go func() {
err := proxy.handleConnection(conn)
if err == nil {
return
}
// io.EOF means connection was closed
if errors.Cause(err) == io.EOF {
err = errors.Wrap(
err,
fmt.Sprintf(
"connection closed early on %v\n",
conn.LocalAddr(),
),
)
}
logger.Errorf("Failed on handle connection: %s", err)
}()
}
}()
return nil
}
// Stop terminates proxyService by closing the listening net.Listener
func (proxy *proxyService) Stop() error {
proxy.logger.Infof("Stopping service")
proxy.done = true
return proxy.listener.Close()
}