Skip to content

Commit

Permalink
Merge remote-tracking branch 'origin/master' into smallinsky/fix-tls-…
Browse files Browse the repository at this point in the history
…routing-jumphost
  • Loading branch information
smallinsky committed Mar 25, 2022
2 parents 78fb340 + 335adf1 commit efd8191
Show file tree
Hide file tree
Showing 114 changed files with 6,803 additions and 4,701 deletions.
151 changes: 79 additions & 72 deletions Cargo.lock

Large diffs are not rendered by default.

8 changes: 4 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
<div align="center">
<img src="https://goteleport.com/blog/images/2020/gravitational-is-teleport-header.png" width=750/>
<img src="./assets/img/readme-header.png" width=750/>
<div align="center" style="padding: 25px">
<a href="https://goteleport.com/docs/">
<img src="https://img.shields.io/badge/Teleport-8.0-651FFF.svg" />
<a href="https://goteleport.com/teleport/download">
<img src="https://img.shields.io/github/v/release/gravitational/teleport?sort=semver&label=Release&color=651FFF" />
</a>
<a href="https://golang.org/">
<img src="https://img.shields.io/badge/Go-1.17-7fd5ea.svg" />
<img src="https://img.shields.io/github/go-mod/go-version/gravitational/teleport?color=7fd5ea" />
</a>
<a href="https://github.com/gravitational/teleport/blob/master/CODE_OF_CONDUCT.md">
<img src="https://img.shields.io/badge/Contribute-🙌-green.svg" />
Expand Down
6 changes: 4 additions & 2 deletions api/client/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -288,7 +288,7 @@ type (

// authConnect connects to the Teleport Auth Server directly.
func authConnect(ctx context.Context, params connectParams) (*Client, error) {
dialer := NewDirectDialer(params.cfg.KeepAlivePeriod, params.cfg.DialTimeout)
dialer := NewDialer(params.cfg.KeepAlivePeriod, params.cfg.DialTimeout)
clt := newClient(params.cfg, dialer, params.tlsConfig)
if err := clt.dialGRPC(ctx, params.addr); err != nil {
return nil, trace.Wrap(err, "failed to connect to addr %v as an auth server", params.addr)
Expand Down Expand Up @@ -358,7 +358,7 @@ func (c *Client) dialGRPC(ctx context.Context, addr string) error {
dialContext, cancel := context.WithTimeout(ctx, c.c.DialTimeout)
defer cancel()

dialOpts := append([]grpc.DialOption{}, c.c.DialOpts...)
var dialOpts []grpc.DialOption
dialOpts = append(dialOpts, grpc.WithContextDialer(c.grpcDialer()))
dialOpts = append(dialOpts,
grpc.WithUnaryInterceptor(metadata.UnaryClientInterceptor),
Expand All @@ -368,6 +368,8 @@ func (c *Client) dialGRPC(ctx context.Context, addr string) error {
if c.tlsConfig != nil {
dialOpts = append(dialOpts, grpc.WithTransportCredentials(credentials.NewTLS(c.tlsConfig)))
}
// must come last, otherwise provided opts may get clobbered by defaults above
dialOpts = append(dialOpts, c.c.DialOpts...)

var err error
if c.conn, err = grpc.DialContext(dialContext, addr, dialOpts...); err != nil {
Expand Down
24 changes: 19 additions & 5 deletions api/client/contextdialer.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,20 +44,33 @@ func (f ContextDialerFunc) DialContext(ctx context.Context, network, addr string
return f(ctx, network, addr)
}

// NewDirectDialer makes a new dialer to connect directly to an Auth server.
func NewDirectDialer(keepAlivePeriod, dialTimeout time.Duration) ContextDialer {
// newDirectDialer makes a new dialer to connect directly to an Auth server.
func newDirectDialer(keepAlivePeriod, dialTimeout time.Duration) ContextDialer {
return &net.Dialer{
Timeout: dialTimeout,
KeepAlive: keepAlivePeriod,
}
}

// NewDialer makes a new dialer that connects to an Auth server either directly or via an HTTP proxy, depending
// on the environment.
func NewDialer(keepAlivePeriod, dialTimeout time.Duration) ContextDialer {
return ContextDialerFunc(func(ctx context.Context, network, addr string) (net.Conn, error) {
dialer := newDirectDialer(keepAlivePeriod, dialTimeout)
if proxyAddr := GetProxyAddress(addr); proxyAddr != "" {
return DialProxyWithDialer(ctx, proxyAddr, addr, dialer)
}
return dialer.DialContext(ctx, network, addr)
})
}

// NewProxyDialer makes a dialer to connect to an Auth server through the SSH reverse tunnel on the proxy.
// The dialer will ping the web client to discover the tunnel proxy address on each dial.
func NewProxyDialer(ssh ssh.ClientConfig, keepAlivePeriod, dialTimeout time.Duration, discoveryAddr string, insecure bool) ContextDialer {
dialer := newTunnelDialer(ssh, keepAlivePeriod, dialTimeout)
return ContextDialerFunc(func(ctx context.Context, network, _ string) (conn net.Conn, err error) {
tunnelAddr, err := webclient.GetTunnelAddr(ctx, discoveryAddr, insecure, nil)
tunnelAddr, err := webclient.GetTunnelAddr(
&webclient.Config{Context: ctx, ProxyAddr: discoveryAddr, Insecure: insecure})
if err != nil {
return nil, trace.Wrap(err)
}
Expand All @@ -72,7 +85,7 @@ func NewProxyDialer(ssh ssh.ClientConfig, keepAlivePeriod, dialTimeout time.Dura

// newTunnelDialer makes a dialer to connect to an Auth server through the SSH reverse tunnel on the proxy.
func newTunnelDialer(ssh ssh.ClientConfig, keepAlivePeriod, dialTimeout time.Duration) ContextDialer {
dialer := NewDirectDialer(keepAlivePeriod, dialTimeout)
dialer := newDirectDialer(keepAlivePeriod, dialTimeout)
return ContextDialerFunc(func(ctx context.Context, network, addr string) (conn net.Conn, err error) {
conn, err = dialer.DialContext(ctx, network, addr)
if err != nil {
Expand All @@ -91,7 +104,8 @@ func newTunnelDialer(ssh ssh.ClientConfig, keepAlivePeriod, dialTimeout time.Dur
// through the SSH reverse tunnel on the proxy.
func newTLSRoutingTunnelDialer(ssh ssh.ClientConfig, keepAlivePeriod, dialTimeout time.Duration, discoveryAddr string, insecure bool) ContextDialer {
return ContextDialerFunc(func(ctx context.Context, network, addr string) (conn net.Conn, err error) {
tunnelAddr, err := webclient.GetTunnelAddr(ctx, discoveryAddr, insecure, nil)
tunnelAddr, err := webclient.GetTunnelAddr(
&webclient.Config{Context: ctx, ProxyAddr: discoveryAddr, Insecure: insecure})
if err != nil {
return nil, trace.Wrap(err)
}
Expand Down
6 changes: 3 additions & 3 deletions lib/utils/proxy/noproxy.go → api/client/noproxy.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,13 @@
// This is the low-level Transport implementation of RoundTripper.
// The high-level interface is in client.go.

package proxy
package client

import (
"os"
"strings"

"github.com/gravitational/teleport"
"github.com/gravitational/teleport/api/constants"
)

// useProxy reports whether requests to addr should use a proxy,
Expand All @@ -24,7 +24,7 @@ func useProxy(addr string) bool {
return true
}
var noProxy string
for _, env := range []string{teleport.NoProxy, strings.ToLower(teleport.NoProxy)} {
for _, env := range []string{constants.NoProxy, strings.ToLower(constants.NoProxy)} {
noProxy = os.Getenv(env)
if noProxy != "" {
break
Expand Down
150 changes: 150 additions & 0 deletions api/client/proxy.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
/*
Copyright 2022 Gravitational, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package client

import (
"bufio"
"context"
"net"
"net/http"
"net/url"
"os"
"strings"

"github.com/gravitational/teleport/api/constants"
"github.com/gravitational/trace"
log "github.com/sirupsen/logrus"
)

// DialProxy creates a connection to a server via an HTTP Proxy.
func DialProxy(ctx context.Context, proxyAddr, addr string) (net.Conn, error) {
return DialProxyWithDialer(ctx, proxyAddr, addr, &net.Dialer{})
}

// DialProxyWithDialer creates a connection to a server via an HTTP Proxy using a specified dialer.
func DialProxyWithDialer(ctx context.Context, proxyAddr, addr string, dialer ContextDialer) (net.Conn, error) {
conn, err := dialer.DialContext(ctx, "tcp", proxyAddr)
if err != nil {
log.Warnf("Unable to dial to proxy: %v: %v.", proxyAddr, err)
return nil, trace.ConvertSystemError(err)
}

connectReq := &http.Request{
Method: http.MethodConnect,
URL: &url.URL{Opaque: addr},
Host: addr,
Header: make(http.Header),
}

if err := connectReq.Write(conn); err != nil {
log.Warnf("Unable to write to proxy: %v.", err)
return nil, trace.Wrap(err)
}

// Read in the response. http.ReadResponse will read in the status line, mime
// headers, and potentially part of the response body. the body itself will
// not be read, but kept around so it can be read later.
br := bufio.NewReader(conn)
// Per the above comment, we're only using ReadResponse to check the status
// and then hand off the underlying connection to the caller.
// resp.Body.Close() would drain conn and close it, we don't need to do it
// here. Disabling bodyclose linter for this edge case.
//nolint:bodyclose
resp, err := http.ReadResponse(br, connectReq)
if err != nil {
conn.Close()
log.Warnf("Unable to read response: %v.", err)
return nil, trace.Wrap(err)
}
if resp.StatusCode != http.StatusOK {
conn.Close()
return nil, trace.BadParameter("unable to proxy connection: %v", resp.Status)
}

// Return a bufferedConn that wraps a net.Conn and a *bufio.Reader. this
// needs to be done because http.ReadResponse will buffer part of the
// response body in the *bufio.Reader that was passed in. reads must first
// come from anything buffered, then from the underlying connection otherwise
// data will be lost.
return &bufferedConn{
Conn: conn,
reader: br,
}, nil
}

// GetProxyAddress gets the HTTP proxy address to use for a given address, if any.
func GetProxyAddress(addr string) string {
envs := []string{
constants.HTTPSProxy,
strings.ToLower(constants.HTTPSProxy),
constants.HTTPProxy,
strings.ToLower(constants.HTTPProxy),
}

for _, v := range envs {
envAddr := os.Getenv(v)
if envAddr == "" {
continue
}
proxyAddr, err := parse(envAddr)
if err != nil {
log.Debugf("Unable to parse environment variable %q: %q.", v, envAddr)
continue
}
log.Debugf("Successfully parsed environment variable %q: %q to %q.", v, envAddr, proxyAddr)
if !useProxy(addr) {
log.Debugf("Matched NO_PROXY override for %q: %q, going to ignore proxy variable.", v, envAddr)
return ""
}
return proxyAddr
}

log.Debugf("No valid environment variables found.")
return ""
}

// bufferedConn is used when part of the data on a connection has already been
// read by a *bufio.Reader. Reads will first try and read from the
// *bufio.Reader and when everything has been read, reads will go to the
// underlying connection.
type bufferedConn struct {
net.Conn
reader *bufio.Reader
}

// Read first reads from the *bufio.Reader any data that has already been
// buffered. Once all buffered data has been read, reads go to the net.Conn.
func (bc *bufferedConn) Read(b []byte) (n int, err error) {
if bc.reader.Buffered() > 0 {
return bc.reader.Read(b)
}
return bc.Conn.Read(b)
}

// parse will extract the host:port of the proxy to dial to. If the
// value is not prefixed by "http", then it will prepend "http" and try.
func parse(addr string) (string, error) {
proxyurl, err := url.Parse(addr)
if err != nil || !strings.HasPrefix(proxyurl.Scheme, "http") {
proxyurl, err = url.Parse("http://" + addr)
if err != nil {
return "", trace.Wrap(err)
}
}

return proxyurl.Host, nil
}
11 changes: 2 additions & 9 deletions lib/utils/proxy/proxy_test.go → api/client/proxy_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,22 +14,15 @@ See the License for the specific language governing permissions and
limitations under the License.
*/

package proxy
package client

import (
"fmt"
"os"
"testing"

"github.com/gravitational/teleport/lib/utils"
"github.com/stretchr/testify/require"
)

func TestMain(m *testing.M) {
utils.InitLoggerForTests()
os.Exit(m.Run())
}

func TestGetProxyAddress(t *testing.T) {
type env struct {
name string
Expand Down Expand Up @@ -96,7 +89,7 @@ func TestGetProxyAddress(t *testing.T) {
for _, env := range tt.env {
t.Setenv(env.name, env.val)
}
p := getProxyAddress(tt.targetAddr)
p := GetProxyAddress(tt.targetAddr)
require.Equal(t, tt.proxyAddr, p)
})
}
Expand Down
Loading

0 comments on commit efd8191

Please sign in to comment.