github.com/gravitational/teleport/api@v0.0.0-20240507183017-3110591cbafc/utils/sshutils/conn.go (about)

     1  /*
     2  Copyright 2021 Gravitational, Inc.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package sshutils
    18  
    19  import (
    20  	"bytes"
    21  	"encoding/json"
    22  	"fmt"
    23  	"io"
    24  
    25  	"github.com/gravitational/trace"
    26  	"golang.org/x/crypto/ssh"
    27  
    28  	"github.com/gravitational/teleport/api/constants"
    29  	"github.com/gravitational/teleport/api/types"
    30  )
    31  
    32  // ConnectProxyTransport opens a channel over the remote tunnel and connects
    33  // to the requested host.
    34  //
    35  // Returns the net.Conn wrapper over an SSH channel, whether the provided ssh.Conn
    36  // should be considered invalid due to errors opening or sending a request to the
    37  // channel while setting up the ChConn, and any error that occurs.
    38  func ConnectProxyTransport(sconn ssh.Conn, req *DialReq, exclusive bool) (conn *ChConn, invalid bool, err error) {
    39  	if err := req.CheckAndSetDefaults(); err != nil {
    40  		return nil, false, trace.Wrap(err)
    41  	}
    42  
    43  	payload, err := json.Marshal(req)
    44  	if err != nil {
    45  		return nil, false, trace.Wrap(err)
    46  	}
    47  
    48  	channel, reqC, err := sconn.OpenChannel(constants.ChanTransport, nil)
    49  	if err != nil {
    50  		return nil, true, trace.Wrap(err)
    51  	}
    52  
    53  	// DiscardRequests will return when the channel or underlying connection is closed.
    54  	go ssh.DiscardRequests(reqC)
    55  
    56  	// Send a special SSH out-of-band request called "teleport-transport"
    57  	// the agent on the other side will create a new TCP/IP connection to
    58  	// 'addr' on its network and will start proxying that connection over
    59  	// this SSH channel.
    60  	ok, err := channel.SendRequest(constants.ChanTransportDialReq, true, payload)
    61  	if err != nil {
    62  		return nil, true, trace.NewAggregate(trace.Wrap(err), channel.Close())
    63  	}
    64  	if !ok {
    65  		defer channel.Close()
    66  
    67  		// Pull the error message from the tunnel client (remote cluster)
    68  		// passed to us via stderr.
    69  		errMessageBytes, _ := io.ReadAll(channel.Stderr())
    70  		errMessage := string(bytes.TrimSpace(errMessageBytes))
    71  		if len(errMessage) == 0 {
    72  			errMessage = fmt.Sprintf("failed connecting to %v [%v]", req.Address, req.ServerID)
    73  		}
    74  		return nil, false, trace.Errorf(errMessage)
    75  	}
    76  
    77  	if exclusive {
    78  		return NewExclusiveChConn(sconn, channel), false, nil
    79  	}
    80  
    81  	return NewChConn(sconn, channel), false, nil
    82  }
    83  
    84  // DialReq is a request for the address to connect to. Supports special
    85  // non-resolvable addresses and search names if connection over a tunnel.
    86  type DialReq struct {
    87  	// Address is the target host to make a connection to.
    88  	Address string `json:"address,omitempty"`
    89  
    90  	// ServerID is the hostUUID.clusterName of the node. ServerID is used when
    91  	// dialing through a tunnel to SSH and application nodes.
    92  	ServerID string `json:"server_id,omitempty"`
    93  
    94  	// ConnType is the type of connection requested, either node or application.
    95  	ConnType types.TunnelType `json:"conn_type"`
    96  
    97  	// ClientSrcAddr is the original observed client address, it is used to propagate
    98  	// correct client IP through indirect connections inside teleport
    99  	ClientSrcAddr string `json:"client_src_addr,omitempty"`
   100  
   101  	// ClientDstAddr is the original client's destination address, it is used to propagate
   102  	// correct client point of contact through indirect connections inside teleport
   103  	ClientDstAddr string `json:"client_dst_addr,omitempty"`
   104  
   105  	// IsAgentlessNode specifies whether the target is an agentless node.
   106  	IsAgentlessNode bool `json:"is_agentless_node,omitempty"`
   107  }
   108  
   109  // CheckAndSetDefaults verifies all the values are valid.
   110  func (d *DialReq) CheckAndSetDefaults() error {
   111  	if d.ConnType == "" {
   112  		d.ConnType = types.NodeTunnel
   113  	}
   114  
   115  	if d.Address == "" && d.ServerID == "" {
   116  		return trace.BadParameter("serverID or address required")
   117  	}
   118  	return nil
   119  }