2018-10-08 19:20:28 +00:00
package tunnel
2018-05-01 23:45:06 +00:00
import (
2020-11-02 11:21:34 +00:00
"crypto/tls"
2018-05-01 23:45:06 +00:00
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
2019-06-17 21:18:47 +00:00
"github.com/cloudflare/cloudflared/cmd/cloudflared/buildinfo"
2018-10-08 19:20:28 +00:00
"github.com/cloudflare/cloudflared/cmd/cloudflared/config"
2020-10-08 10:12:26 +00:00
"github.com/cloudflare/cloudflared/connection"
2020-10-14 10:28:07 +00:00
"github.com/cloudflare/cloudflared/edgediscovery"
2020-10-08 10:12:26 +00:00
"github.com/cloudflare/cloudflared/h2mux"
2020-10-09 00:12:29 +00:00
"github.com/cloudflare/cloudflared/ingress"
2020-04-29 20:51:32 +00:00
"github.com/cloudflare/cloudflared/logger"
2018-05-01 23:45:06 +00:00
"github.com/cloudflare/cloudflared/origin"
"github.com/cloudflare/cloudflared/tlsconfig"
tunnelpogs "github.com/cloudflare/cloudflared/tunnelrpc/pogs"
"github.com/cloudflare/cloudflared/validation"
2019-03-28 17:58:23 +00:00
"github.com/google/uuid"
2018-05-01 23:45:06 +00:00
"github.com/mitchellh/go-homedir"
"github.com/pkg/errors"
2020-08-05 10:49:53 +00:00
"github.com/urfave/cli/v2"
2019-03-28 17:58:23 +00:00
"golang.org/x/crypto/ssh/terminal"
2018-05-01 23:45:06 +00:00
)
var (
2018-10-08 19:20:28 +00:00
developerPortal = "https://developers.cloudflare.com/argo-tunnel"
quickStartUrl = developerPortal + "/quickstart/quickstart/"
serviceUrl = developerPortal + "/reference/service/"
argumentsUrl = developerPortal + "/reference/arguments/"
2018-05-01 23:45:06 +00:00
)
2020-08-14 20:52:47 +00:00
// returns the first path that contains a cert.pem file. If none of the DefaultConfigSearchDirectories
2018-10-08 19:20:28 +00:00
// contains a cert.pem file, return empty string
2018-05-01 23:45:06 +00:00
func findDefaultOriginCertPath ( ) string {
2020-08-14 20:52:47 +00:00
for _ , defaultConfigDir := range config . DefaultConfigSearchDirectories ( ) {
2018-10-08 19:20:28 +00:00
originCertPath , _ := homedir . Expand ( filepath . Join ( defaultConfigDir , config . DefaultCredentialFile ) )
if ok , _ := config . FileExists ( originCertPath ) ; ok {
2018-05-01 23:45:06 +00:00
return originCertPath
}
}
return ""
}
2020-04-29 20:51:32 +00:00
func generateRandomClientID ( logger logger . Service ) ( string , error ) {
2019-03-28 17:58:23 +00:00
u , err := uuid . NewRandom ( )
if err != nil {
2020-04-29 20:51:32 +00:00
logger . Errorf ( "couldn't create UUID for client ID %s" , err )
2019-03-28 17:58:23 +00:00
return "" , err
}
return u . String ( ) , nil
2018-05-01 23:45:06 +00:00
}
2020-04-29 20:51:32 +00:00
func logClientOptions ( c * cli . Context , logger logger . Service ) {
2018-05-01 23:45:06 +00:00
flags := make ( map [ string ] interface { } )
for _ , flag := range c . LocalFlagNames ( ) {
flags [ flag ] = c . Generic ( flag )
}
2019-03-08 08:36:24 +00:00
sliceFlags := [ ] string { "header" , "tag" , "proxy-dns-upstream" , "upstream" , "edge" }
for _ , sliceFlag := range sliceFlags {
if len ( c . StringSlice ( sliceFlag ) ) > 0 {
flags [ sliceFlag ] = strings . Join ( c . StringSlice ( sliceFlag ) , ", " )
}
}
2018-05-01 23:45:06 +00:00
if len ( flags ) > 0 {
2020-04-29 20:51:32 +00:00
logger . Infof ( "Environment variables %v" , flags )
2018-05-01 23:45:06 +00:00
}
envs := make ( map [ string ] string )
// Find env variables for Argo Tunnel
for _ , env := range os . Environ ( ) {
// All Argo Tunnel env variables start with TUNNEL_
if strings . Contains ( env , "TUNNEL_" ) {
vars := strings . Split ( env , "=" )
if len ( vars ) == 2 {
envs [ vars [ 0 ] ] = vars [ 1 ]
}
}
}
if len ( envs ) > 0 {
logger . Infof ( "Environmental variables %v" , envs )
}
}
func dnsProxyStandAlone ( c * cli . Context ) bool {
return c . IsSet ( "proxy-dns" ) && ( ! c . IsSet ( "hostname" ) && ! c . IsSet ( "tag" ) && ! c . IsSet ( "hello-world" ) )
}
2020-04-29 20:51:32 +00:00
func findOriginCert ( c * cli . Context , logger logger . Service ) ( string , error ) {
2020-05-21 20:36:49 +00:00
originCertPath := c . String ( "origincert" )
if originCertPath == "" {
2020-10-15 20:08:57 +00:00
logger . Infof ( "Cannot determine default origin certificate path. No file %s in %v" , config . DefaultCredentialFile , config . DefaultConfigSearchDirectories ( ) )
2018-05-01 23:45:06 +00:00
if isRunningFromTerminal ( ) {
logger . Errorf ( "You need to specify the origin certificate path with --origincert option, or set TUNNEL_ORIGIN_CERT environment variable. See %s for more information." , argumentsUrl )
2020-05-21 20:36:49 +00:00
return "" , fmt . Errorf ( "Client didn't specify origincert path when running from terminal" )
2018-05-01 23:45:06 +00:00
} else {
logger . Errorf ( "You need to specify the origin certificate path by specifying the origincert option in the configuration file, or set TUNNEL_ORIGIN_CERT environment variable. See %s for more information." , serviceUrl )
2020-05-21 20:36:49 +00:00
return "" , fmt . Errorf ( "Client didn't specify origincert path" )
2018-05-01 23:45:06 +00:00
}
}
2020-05-21 20:36:49 +00:00
var err error
originCertPath , err = homedir . Expand ( originCertPath )
2018-05-01 23:45:06 +00:00
if err != nil {
2020-04-29 20:51:32 +00:00
logger . Errorf ( "Cannot resolve path %s: %s" , originCertPath , err )
2020-05-21 20:36:49 +00:00
return "" , fmt . Errorf ( "Cannot resolve path %s" , originCertPath )
2018-05-01 23:45:06 +00:00
}
2020-05-21 20:36:49 +00:00
// Check that the user has acquired a certificate using the login command
2018-10-08 19:20:28 +00:00
ok , err := config . FileExists ( originCertPath )
2018-05-01 23:45:06 +00:00
if err != nil {
2020-05-21 20:36:49 +00:00
logger . Errorf ( "Cannot check if origin cert exists at path %s" , originCertPath )
return "" , fmt . Errorf ( "Cannot check if origin cert exists at path %s" , originCertPath )
2018-05-01 23:45:06 +00:00
}
if ! ok {
logger . Errorf ( ` Cannot find a valid certificate for your origin at the path :
% s
If the path above is wrong , specify the path with the - origincert option .
If you don ' t have a certificate signed by Cloudflare , run the command :
% s login
` , originCertPath , os . Args [ 0 ] )
2020-05-21 20:36:49 +00:00
return "" , fmt . Errorf ( "Cannot find a valid certificate at the path %s" , originCertPath )
2018-05-01 23:45:06 +00:00
}
2020-05-21 20:36:49 +00:00
return originCertPath , nil
}
2020-04-29 20:51:32 +00:00
func readOriginCert ( originCertPath string , logger logger . Service ) ( [ ] byte , error ) {
2020-05-21 20:36:49 +00:00
logger . Debugf ( "Reading origin cert from %s" , originCertPath )
2018-05-01 23:45:06 +00:00
// Easier to send the certificate as []byte via RPC than decoding it at this point
originCert , err := ioutil . ReadFile ( originCertPath )
if err != nil {
2020-04-29 20:51:32 +00:00
logger . Errorf ( "Cannot read %s to load origin certificate: %s" , originCertPath , err )
2018-05-01 23:45:06 +00:00
return nil , fmt . Errorf ( "Cannot read %s to load origin certificate" , originCertPath )
}
return originCert , nil
}
2020-04-29 20:51:32 +00:00
func getOriginCert ( c * cli . Context , logger logger . Service ) ( [ ] byte , error ) {
if originCertPath , err := findOriginCert ( c , logger ) ; err != nil {
2020-05-21 20:36:49 +00:00
return nil , err
} else {
2020-04-29 20:51:32 +00:00
return readOriginCert ( originCertPath , logger )
2020-05-21 20:36:49 +00:00
}
}
2019-02-28 22:56:01 +00:00
func prepareTunnelConfig (
c * cli . Context ,
2019-06-17 21:18:47 +00:00
buildInfo * buildinfo . BuildInfo ,
2020-04-29 20:51:32 +00:00
version string ,
logger logger . Service ,
transportLogger logger . Service ,
2020-10-08 10:12:26 +00:00
namedTunnel * connection . NamedTunnelConfig ,
2020-11-30 20:05:37 +00:00
isUIEnabled bool ,
eventChans [ ] chan connection . Event ,
2020-11-02 11:21:34 +00:00
) ( * origin . TunnelConfig , ingress . Ingress , error ) {
2020-09-11 22:02:34 +00:00
isNamedTunnel := namedTunnel != nil
2020-06-25 18:25:39 +00:00
2018-05-01 23:45:06 +00:00
hostname , err := validation . ValidateHostname ( c . String ( "hostname" ) )
if err != nil {
2020-04-29 20:51:32 +00:00
logger . Errorf ( "Invalid hostname: %s" , err )
2020-11-02 11:21:34 +00:00
return nil , ingress . Ingress { } , errors . Wrap ( err , "Invalid hostname" )
2018-05-01 23:45:06 +00:00
}
2019-03-22 17:00:57 +00:00
isFreeTunnel := hostname == ""
2018-05-01 23:45:06 +00:00
clientID := c . String ( "id" )
if ! c . IsSet ( "id" ) {
2019-03-28 17:58:23 +00:00
clientID , err = generateRandomClientID ( logger )
if err != nil {
2020-11-02 11:21:34 +00:00
return nil , ingress . Ingress { } , err
2019-03-28 17:58:23 +00:00
}
2018-05-01 23:45:06 +00:00
}
tags , err := NewTagSliceFromCLI ( c . StringSlice ( "tag" ) )
if err != nil {
2020-04-29 20:51:32 +00:00
logger . Errorf ( "Tag parse failure: %s" , err )
2020-11-02 11:21:34 +00:00
return nil , ingress . Ingress { } , errors . Wrap ( err , "Tag parse failure" )
2018-05-01 23:45:06 +00:00
}
tags = append ( tags , tunnelpogs . Tag { Name : "ID" , Value : clientID } )
2019-03-22 17:00:57 +00:00
var originCert [ ] byte
if ! isFreeTunnel {
2020-04-29 20:51:32 +00:00
originCert , err = getOriginCert ( c , logger )
2019-03-22 17:00:57 +00:00
if err != nil {
2020-11-02 11:21:34 +00:00
return nil , ingress . Ingress { } , errors . Wrap ( err , "Error getting origin cert" )
2019-03-22 17:00:57 +00:00
}
2018-05-01 23:45:06 +00:00
}
2020-10-08 10:12:26 +00:00
var (
ingressRules ingress . Ingress
classicTunnel * connection . ClassicTunnelConfig
)
if isNamedTunnel {
2020-10-09 00:12:29 +00:00
clientUUID , err := uuid . NewRandom ( )
if err != nil {
2020-11-02 11:21:34 +00:00
return nil , ingress . Ingress { } , errors . Wrap ( err , "can't generate clientUUID" )
2020-10-09 00:12:29 +00:00
}
namedTunnel . Client = tunnelpogs . ClientInfo {
ClientID : clientUUID [ : ] ,
Features : [ ] string { origin . FeatureSerializedHeaders } ,
Version : version ,
Arch : fmt . Sprintf ( "%s_%s" , buildInfo . GoOS , buildInfo . GoArch ) ,
}
2020-10-30 21:37:40 +00:00
ingressRules , err = ingress . ParseIngress ( config . GetConfiguration ( ) )
2020-10-12 17:54:15 +00:00
if err != nil && err != ingress . ErrNoIngressRules {
2020-11-02 11:21:34 +00:00
return nil , ingress . Ingress { } , err
2020-10-09 00:12:29 +00:00
}
2020-10-15 17:41:50 +00:00
if ! ingressRules . IsEmpty ( ) && c . IsSet ( "url" ) {
2020-11-02 11:21:34 +00:00
return nil , ingress . Ingress { } , ingress . ErrURLIncompatibleWithIngress
2020-10-09 00:12:29 +00:00
}
2020-10-08 10:12:26 +00:00
} else {
classicTunnel = & connection . ClassicTunnelConfig {
Hostname : hostname ,
OriginCert : originCert ,
// turn off use of reconnect token and auth refresh when using named tunnels
UseReconnectToken : ! isNamedTunnel && c . Bool ( "use-reconnect-token" ) ,
}
2020-10-09 00:12:29 +00:00
}
2020-10-15 21:41:03 +00:00
// Convert single-origin configuration into multi-origin configuration.
2020-10-15 17:41:50 +00:00
if ingressRules . IsEmpty ( ) {
2020-11-02 11:21:34 +00:00
ingressRules , err = ingress . NewSingleOrigin ( c , ! isNamedTunnel , logger )
2020-10-09 00:12:29 +00:00
if err != nil {
2020-11-02 11:21:34 +00:00
return nil , ingress . Ingress { } , err
2020-05-04 20:15:17 +00:00
}
2018-10-08 19:20:28 +00:00
}
2020-10-14 13:42:00 +00:00
protocolSelector , err := connection . NewProtocolSelector ( c . String ( "protocol" ) , namedTunnel , edgediscovery . HTTP2Percentage , origin . ResolveTTL , logger )
2020-10-14 10:28:07 +00:00
if err != nil {
2020-11-02 11:21:34 +00:00
return nil , ingress . Ingress { } , err
2020-10-14 10:28:07 +00:00
}
2020-10-14 13:42:00 +00:00
logger . Infof ( "Initial protocol %s" , protocolSelector . Current ( ) )
edgeTLSConfigs := make ( map [ connection . Protocol ] * tls . Config , len ( connection . ProtocolList ) )
for _ , p := range connection . ProtocolList {
edgeTLSConfig , err := tlsconfig . CreateTunnelConfig ( c , p . ServerName ( ) )
if err != nil {
2020-11-02 11:21:34 +00:00
return nil , ingress . Ingress { } , errors . Wrap ( err , "unable to create TLS config to connect with edge" )
2020-10-14 13:42:00 +00:00
}
edgeTLSConfigs [ p ] = edgeTLSConfig
2018-11-15 15:43:50 +00:00
}
2020-10-08 10:12:26 +00:00
2020-11-02 11:21:34 +00:00
originClient := origin . NewClient ( ingressRules , tags , logger )
2020-10-14 13:42:00 +00:00
connectionConfig := & connection . Config {
2020-10-08 10:12:26 +00:00
OriginClient : originClient ,
GracePeriod : c . Duration ( "grace-period" ) ,
ReplaceExisting : c . Bool ( "force" ) ,
}
muxerConfig := & connection . MuxerConfig {
2020-06-25 18:25:39 +00:00
HeartbeatInterval : c . Duration ( "heartbeat-interval" ) ,
MaxHeartbeats : c . Uint64 ( "heartbeat-count" ) ,
2020-10-08 10:12:26 +00:00
CompressionSetting : h2mux . CompressionSetting ( c . Uint64 ( "compression-quality" ) ) ,
2020-06-25 18:25:39 +00:00
MetricsUpdateFreq : c . Duration ( "metrics-update-freq" ) ,
2020-10-08 10:12:26 +00:00
}
return & origin . TunnelConfig {
2020-10-14 13:42:00 +00:00
ConnectionConfig : connectionConfig ,
2020-10-08 10:12:26 +00:00
BuildInfo : buildInfo ,
ClientID : clientID ,
EdgeAddrs : c . StringSlice ( "edge" ) ,
HAConnections : c . Int ( "ha-connections" ) ,
IncidentLookup : origin . NewIncidentLookup ( ) ,
IsAutoupdated : c . Bool ( "is-autoupdated" ) ,
IsFreeTunnel : isFreeTunnel ,
LBPool : c . String ( "lb-pool" ) ,
2020-11-02 11:21:34 +00:00
Tags : tags ,
2020-10-08 10:12:26 +00:00
Logger : logger ,
2020-11-30 20:05:37 +00:00
Observer : connection . NewObserver ( transportLogger , eventChans , isUIEnabled ) ,
2020-10-08 10:12:26 +00:00
ReportedVersion : version ,
Retries : c . Uint ( "retries" ) ,
RunFromTerminal : isRunningFromTerminal ( ) ,
NamedTunnel : namedTunnel ,
ClassicTunnel : classicTunnel ,
MuxerConfig : muxerConfig ,
2020-11-30 20:05:37 +00:00
TunnelEventChans : eventChans ,
2020-10-14 13:42:00 +00:00
ProtocolSelector : protocolSelector ,
EdgeTLSConfigs : edgeTLSConfigs ,
2020-11-02 11:21:34 +00:00
} , ingressRules , nil
2018-05-01 23:45:06 +00:00
}
2018-10-08 19:20:28 +00:00
func isRunningFromTerminal ( ) bool {
return terminal . IsTerminal ( int ( os . Stdout . Fd ( ) ) )
}