From 7909b240896756bbbbda717d2d1a3a197f63744c Mon Sep 17 00:00:00 2001 From: forest Date: Tue, 15 Dec 2020 16:47:26 -0600 Subject: [PATCH 01/36] working on MultiTenantMode support, removing non-TLS mode --- README.md | 2 - main.go | 264 +++++++++++++++++++++---------- tunnel-lib/client.go | 3 - tunnel-lib/proto/proto.go | 3 - tunnel-lib/server.go | 42 +++-- usage-example/client-config.json | 1 - usage-example/server-config.json | 1 - 7 files changed, 204 insertions(+), 112 deletions(-) diff --git a/README.md b/README.md index 4c2b42b..e9535c6 100644 --- a/README.md +++ b/README.md @@ -36,7 +36,6 @@ Starting the "listener" test app. It listens on port 9001. This would be your w "DebugLog": false, "TunnelControlPort": 9056, "ManagementPort": 9057, - "UseTls": true, "CaCertificateFile": "InternalCA+chain.crt", "ServerTlsKeyFile": "localhost.key", "ServerTlsCertificateFile": "localhost+chain.crt" @@ -52,7 +51,6 @@ Starting the tunnel client. Client Identifier: TestClient1 "ServerHost": "localhost", "ServerTunnelControlPort": 9056, "ServerManagementPort": 9057, - "UseTls": true, "ServiceToLocalAddrMap": { "fooService": "127.0.0.1:9001" }, diff --git a/main.go b/main.go index e44fd46..c98d92b 100644 --- a/main.go +++ b/main.go @@ -13,9 +13,11 @@ import ( "log" "net" "net/http" + "net/url" "os" "path" "path/filepath" + "regexp" "strings" "sync" "time" @@ -33,7 +35,18 @@ type ServerConfig struct { // based on domain users/email addresses. Domain string - UseTls bool + // MultiTenantMode ON: + // tenantId is required. ClientId must be formatted `.` + // clients will not be allowed to register listeners capturing all packets on a given port, + // they must specify a hostname, and they must prove that they own it (via a TXT record for example). + // Exception: Each client will get a few allocated ports for SSH & maybe etc??? + // + // MultiTenantMode OFF: + // tenantId is N/A. ClientId must be formatted `` + // clients can register listeners with any hostname including null, on any open port. + // + MultiTenantMode bool + CaCertificateFilesGlob string ServerTlsKeyFile string ServerTlsCertificateFile string @@ -43,7 +56,6 @@ type ClientConfig struct { DebugLog bool ClientIdentifier string ServerAddr string - UseTls bool ServiceToLocalAddrMap *map[string]string CaCertificateFilesGlob string ClientTlsKeyFile string @@ -66,6 +78,7 @@ type ClientState struct { } type ManagementHttpHandler struct { + Domain string ControlHandler http.Handler } @@ -77,15 +90,15 @@ type LiveConfigUpdate struct { type adminAPI struct{} // Server State -var listeners []ListenerConfig +var listenersByTenant map[string][]ListenerConfig var clientStatesMutex = &sync.Mutex{} -var clientStates map[string]ClientState +var clientStatesByTenant map[string]map[string]ClientState var server *tunnel.Server // Client State var client *tunnel.Client var tlsClientConfig *tls.Config -var serverURL *string +var serverHostPort *string var serviceToLocalAddrMap *map[string]string func main() { @@ -107,7 +120,7 @@ func main() { } -// admin api handler for /liveconfig over unix socket +// client admin api handler for /liveconfig over unix socket func (handler adminAPI) ServeHTTP(response http.ResponseWriter, request *http.Request) { switch path.Clean(request.URL.Path) { case "/liveconfig": @@ -132,7 +145,7 @@ func (handler adminAPI) ServeHTTP(response http.ResponseWriter, request *http.Re http.Error(response, "500 Listeners json serialization failed", http.StatusInternalServerError) return } - apiURL := fmt.Sprintf("https://%s/tunnels", *serverURL) + apiURL := fmt.Sprintf("https://%s/tunnels", *serverHostPort) tunnelsRequest, err := http.NewRequest("PUT", apiURL, bytes.NewReader(sendBytes)) if err != nil { log.Printf("adminAPI: error creating tunnels request: %+v\n\n", err) @@ -198,44 +211,69 @@ func runClient(configFileName *string) { if err != nil { log.Fatalf("runClient(): can't json.Unmarshal(configBytes, &config) because %s \n", err) } + serviceToLocalAddrMap = config.ServiceToLocalAddrMap - serverURL = &config.ServerAddr + serverHostPort = &config.ServerAddr + serverURLString := fmt.Sprintf("https://%s", *serverHostPort) + serverURL, err := url.Parse(serverURLString) + if err != nil { + log.Fatal(fmt.Errorf("failed to parse the ServerAddr (prefixed with https://) '%s' as a url", serverURLString)) + } configToLog, _ := json.MarshalIndent(config, "", " ") log.Printf("theshold client is starting up using config:\n%s\n", string(configToLog)) dialFunction := net.Dial - if config.UseTls { + cert, err := tls.LoadX509KeyPair(config.ClientTlsCertificateFile, config.ClientTlsKeyFile) + if err != nil { + log.Fatal(err) + } - cert, err := tls.LoadX509KeyPair(config.ClientTlsCertificateFile, config.ClientTlsKeyFile) - if err != nil { - log.Fatal(err) - } + commonName := cert.Leaf.Subject.CommonName + clientIdDomain := strings.Split(commonName, "@") + + if len(clientIdDomain) != 2 { + log.Fatal(fmt.Errorf( + "expected TLS client certificate common name '%s' to match format '@'", commonName, + )) + } + if clientIdDomain[1] != serverURL.Hostname() { + log.Fatal(fmt.Errorf( + "expected TLS client certificate common name domain '%s' to match ServerAddr domain '%s'", + clientIdDomain[1], serverURL.Hostname(), + )) + } + + if clientIdDomain[0] != config.ClientIdentifier { + log.Fatal(fmt.Errorf( + "expected TLS client certificate common name clientId '%s' to match ClientIdentifier '%s'", + clientIdDomain[0], config.ClientIdentifier, + )) + } + + certificates, err := filepath.Glob(config.CaCertificateFilesGlob) + if err != nil { + log.Fatal(err) + } - certificates, err := filepath.Glob(config.CaCertificateFilesGlob) + caCertPool := x509.NewCertPool() + for _, filename := range certificates { + caCert, err := ioutil.ReadFile(filename) if err != nil { log.Fatal(err) } + caCertPool.AppendCertsFromPEM(caCert) + } - caCertPool := x509.NewCertPool() - for _, filename := range certificates { - caCert, err := ioutil.ReadFile(filename) - if err != nil { - log.Fatal(err) - } - caCertPool.AppendCertsFromPEM(caCert) - } - - tlsClientConfig = &tls.Config{ - Certificates: []tls.Certificate{cert}, - RootCAs: caCertPool, - } - tlsClientConfig.BuildNameToCertificate() + tlsClientConfig = &tls.Config{ + Certificates: []tls.Certificate{cert}, + RootCAs: caCertPool, + } + tlsClientConfig.BuildNameToCertificate() - dialFunction = func(network, address string) (net.Conn, error) { - return tls.Dial(network, address, tlsClientConfig) - } + dialFunction = func(network, address string) (net.Conn, error) { + return tls.Dial(network, address, tlsClientConfig) } clientStateChanges := make(chan *tunnel.ClientStateChange) @@ -302,6 +340,50 @@ func runClientAdminApi(config ClientConfig) { } } +func validateCertificate(domain string, request *http.Request) (identifier string, tenantId string, err error) { + if len(request.TLS.PeerCertificates) != 1 { + return "", "", fmt.Errorf("expected exactly 1 TLS client certificate, got %d", len(request.TLS.PeerCertificates)) + } + certCommonName := request.TLS.PeerCertificates[0].Subject.CommonName + clientIdDomain := strings.Split(certCommonName, "@") + if len(clientIdDomain) != 2 { + return "", "", fmt.Errorf( + "expected TLS client certificate common name '%s' to match format '@'", certCommonName, + ) + } + if clientIdDomain[1] != domain { + return "", "", fmt.Errorf( + "expected TLS client certificate common name domain '%s' to match server domain '%s'", + clientIdDomain[1], domain, + ) + } + + identifier = clientIdDomain[0] + nodeId := identifier + + if strings.Contains(identifier, ".") { + tenantIdNodeId := strings.Split(identifier, ".") + if len(tenantIdNodeId) != 2 { + return "", "", fmt.Errorf( + "expected TLS client certificate common name '%s' to match format '.@'", certCommonName, + ) + } + tenantId = tenantIdNodeId[0] + nodeId = tenantIdNodeId[1] + } + + mustMatchRegexp := regexp.MustCompile("(?i)^[a-z0-9]+([a-z0-9-_]*[a-z0-9]+)?$") + if !mustMatchRegexp.MatchString(nodeId) { + return "", "", fmt.Errorf("expected TLS client certificate common name nodeId '%s' to be a valid subdomain", nodeId) + } + + if tenantId != "" && !mustMatchRegexp.MatchString(tenantId) { + return "", "", fmt.Errorf("expected TLS client certificate common name tenantId '%s' to be a valid subdomain", tenantId) + } + + return identifier, tenantId, nil +} + func runServer(configFileName *string) { configBytes := getConfigBytes(configFileName) @@ -319,9 +401,10 @@ func runServer(configFileName *string) { clientStateChangeChannel := make(chan *tunnel.ClientStateChange) tunnelServerConfig := &tunnel.ServerConfig{ - StateChanges: clientStateChangeChannel, - Domain: config.Domain, - DebugLog: config.DebugLog, + StateChanges: clientStateChangeChannel, + ValidateCertificate: validateCertificate, + Domain: config.Domain, + DebugLog: config.DebugLog, } server, err = tunnel.NewServer(tunnelServerConfig) if err != nil { @@ -329,14 +412,27 @@ func runServer(configFileName *string) { os.Exit(1) } - clientStates = make(map[string]ClientState) + clientStatesByTenant = make(map[string]map[string]ClientState) go (func() { for { clientStateChange := <-clientStateChangeChannel clientStatesMutex.Lock() previousState := "" currentState := clientStateChange.Current.String() - fromMap, wasInMap := clientStates[clientStateChange.Identifier] + tenantId := "" + if strings.Contains(clientStateChange.Identifier, ".") { + tenantIdNodeId := strings.Split(clientStateChange.Identifier, ".") + if len(tenantIdNodeId) != 2 { + fmt.Printf("runServer(): go func(): can't handle clientStateChange with malformed Identifier '%s' \n", clientStateChange.Identifier) + break + } + tenantId = tenantIdNodeId[0] + } + + if _, hasTenant := clientStatesByTenant[tenantId]; !hasTenant { + clientStatesByTenant[tenantId] = map[string]ClientState{} + } + fromMap, wasInMap := clientStatesByTenant[tenantId][clientStateChange.Identifier] if wasInMap { previousState = fromMap.CurrentState } else { @@ -346,7 +442,7 @@ func runServer(configFileName *string) { log.Printf("runServer(): recieved a client state change with an error: %s \n", clientStateChange.Error) currentState = "ClientError" } - clientStates[clientStateChange.Identifier] = ClientState{ + clientStatesByTenant[tenantId][clientStateChange.Identifier] = ClientState{ CurrentState: currentState, LastState: previousState, } @@ -354,53 +450,48 @@ func runServer(configFileName *string) { } })() - if config.UseTls { + certificates, err := filepath.Glob(config.CaCertificateFilesGlob) + if err != nil { + log.Fatal(err) + } - certificates, err := filepath.Glob(config.CaCertificateFilesGlob) + caCertPool := x509.NewCertPool() + for _, filename := range certificates { + log.Printf("loading certificate %s, clients who have a key signed by this certificat will be allowed to connect", filename) + caCert, err := ioutil.ReadFile(filename) if err != nil { log.Fatal(err) } + caCertPool.AppendCertsFromPEM(caCert) + } - caCertPool := x509.NewCertPool() - for _, filename := range certificates { - log.Printf("loading certificate %s, clients who have a key signed by this certificat will be allowed to connect", filename) - caCert, err := ioutil.ReadFile(filename) - if err != nil { - log.Fatal(err) - } - caCertPool.AppendCertsFromPEM(caCert) - } - - tlsConfig := &tls.Config{ - ClientCAs: caCertPool, - ClientAuth: tls.RequireAndVerifyClientCert, - } - tlsConfig.BuildNameToCertificate() - - httpsManagementServer := &http.Server{ - Addr: fmt.Sprintf(":%d", config.ListenPort), - TLSConfig: tlsConfig, - Handler: &(ManagementHttpHandler{ControlHandler: server}), - } - - log.Print("runServer(): the server should be running now\n") - err = httpsManagementServer.ListenAndServeTLS(config.ServerTlsCertificateFile, config.ServerTlsKeyFile) - panic(err) - } else { - - log.Print("runServer(): the server should be running now\n") - err = http.ListenAndServe(fmt.Sprintf(":%d", config.ListenPort), &(ManagementHttpHandler{ControlHandler: server})) - panic(err) + tlsConfig := &tls.Config{ + ClientCAs: caCertPool, + ClientAuth: tls.RequireAndVerifyClientCert, } + tlsConfig.BuildNameToCertificate() + + httpsManagementServer := &http.Server{ + Addr: fmt.Sprintf(":%d", config.ListenPort), + TLSConfig: tlsConfig, + Handler: &(ManagementHttpHandler{ + Domain: config.Domain, + ControlHandler: server, + }), + } + + log.Print("runServer(): the server should be running now\n") + err = httpsManagementServer.ListenAndServeTLS(config.ServerTlsCertificateFile, config.ServerTlsKeyFile) + panic(err) } -func setListeners(listenerConfigs []ListenerConfig) (int, string) { +func setListeners(tenantId string, listenerConfigs []ListenerConfig) (int, string) { currentListenersThatCanKeepRunning := make([]ListenerConfig, 0) newListenersThatHaveToBeAdded := make([]ListenerConfig, 0) for _, newListenerConfig := range listenerConfigs { - clientState, everHeardOfClientBefore := clientStates[newListenerConfig.ClientIdentifier] + clientState, everHeardOfClientBefore := clientStatesByTenant[tenantId][newListenerConfig.ClientIdentifier] if !everHeardOfClientBefore { return http.StatusNotFound, fmt.Sprintf("Client %s Not Found", newListenerConfig.ClientIdentifier) } @@ -409,7 +500,7 @@ func setListeners(listenerConfigs []ListenerConfig) (int, string) { } } - for _, existingListener := range listeners { + for _, existingListener := range listenersByTenant[tenantId] { canKeepRunning := false for _, newListenerConfig := range listenerConfigs { if compareListenerConfigs(existingListener, newListenerConfig) { @@ -432,7 +523,7 @@ func setListeners(listenerConfigs []ListenerConfig) (int, string) { for _, newListenerConfig := range listenerConfigs { hasToBeAdded := true - for _, existingListener := range listeners { + for _, existingListener := range listenersByTenant[tenantId] { if compareListenerConfigs(existingListener, newListenerConfig) { hasToBeAdded = false } @@ -466,7 +557,7 @@ func setListeners(listenerConfigs []ListenerConfig) (int, string) { } } - listeners = append(currentListenersThatCanKeepRunning, newListenersThatHaveToBeAdded...) + listenersByTenant[tenantId] = append(currentListenersThatCanKeepRunning, newListenersThatHaveToBeAdded...) return http.StatusOK, "ok" @@ -483,11 +574,24 @@ func compareListenerConfigs(a, b ListenerConfig) bool { func (s *ManagementHttpHandler) ServeHTTP(responseWriter http.ResponseWriter, request *http.Request) { + _, tenantId, err := validateCertificate(s.Domain, request) + if err != nil { + http.Error(responseWriter, fmt.Sprintf("400 bad request: %s", err.Error()), http.StatusBadRequest) + return + } + if _, hasTenant := clientStatesByTenant[tenantId]; !hasTenant { + clientStatesByTenant[tenantId] = map[string]ClientState{} + } + if _, hasTenant := listenersByTenant[tenantId]; !hasTenant { + listenersByTenant[tenantId] = []ListenerConfig{} + } + switch path.Clean(request.URL.Path) { case "/clients": if request.Method == "GET" { clientStatesMutex.Lock() - bytes, err := json.Marshal(clientStates) + + bytes, err := json.Marshal(clientStatesByTenant[tenantId]) clientStatesMutex.Unlock() if err != nil { http.Error(responseWriter, "500 JSON Marshal Error", http.StatusInternalServerError) @@ -497,8 +601,8 @@ func (s *ManagementHttpHandler) ServeHTTP(responseWriter http.ResponseWriter, re responseWriter.Write(bytes) } else { - responseWriter.Header().Set("Allow", "PUT") - http.Error(responseWriter, "405 Method Not Allowed", http.StatusMethodNotAllowed) + responseWriter.Header().Set("Allow", "GET") + http.Error(responseWriter, "405 Method Not Allowed, try GET", http.StatusMethodNotAllowed) } case "/tunnels": if request.Method == "PUT" { @@ -517,7 +621,7 @@ func (s *ManagementHttpHandler) ServeHTTP(responseWriter http.ResponseWriter, re return } - statusCode, errorMessage := setListeners(listenerConfigs) + statusCode, errorMessage := setListeners(tenantId, listenerConfigs) if statusCode != 200 { http.Error(responseWriter, errorMessage, statusCode) @@ -535,14 +639,14 @@ func (s *ManagementHttpHandler) ServeHTTP(responseWriter http.ResponseWriter, re } } else { responseWriter.Header().Set("Allow", "PUT") - http.Error(responseWriter, "405 Method Not Allowed", http.StatusMethodNotAllowed) + http.Error(responseWriter, "405 Method Not Allowed, try PUT", http.StatusMethodNotAllowed) } case "/ping": if request.Method == "GET" { fmt.Fprint(responseWriter, "pong") } else { responseWriter.Header().Set("Allow", "GET") - http.Error(responseWriter, "405 method not allowed", http.StatusMethodNotAllowed) + http.Error(responseWriter, "405 method not allowed, try GET", http.StatusMethodNotAllowed) } default: s.ControlHandler.ServeHTTP(responseWriter, request) diff --git a/tunnel-lib/client.go b/tunnel-lib/client.go index 96f1e63..07ec011 100644 --- a/tunnel-lib/client.go +++ b/tunnel-lib/client.go @@ -431,9 +431,6 @@ func (c *Client) connect(identifier, serverAddr string) error { if err != nil { return fmt.Errorf("error creating request to %s: %s", remoteURL, err) } - - req.Header.Set(proto.ClientIdentifierHeader, identifier) - if c.config.DebugLog { log.Printf("Client.connect(): Writing request to TCP: %+v\n", req) } diff --git a/tunnel-lib/proto/proto.go b/tunnel-lib/proto/proto.go index 5e5a61a..f056cc1 100644 --- a/tunnel-lib/proto/proto.go +++ b/tunnel-lib/proto/proto.go @@ -5,9 +5,6 @@ const ( // ControlPath is http.Handler url path for control connection. ControlPath = "/_controlPath/" - // ClientIdentifierHeader is header carrying information about tunnel identifier. - ClientIdentifierHeader = "X-Threshold-ClientId" - // control messages // Connected is message sent by server to client when control connection was established. diff --git a/tunnel-lib/server.go b/tunnel-lib/server.go index e1d0ef6..6936672 100644 --- a/tunnel-lib/server.go +++ b/tunnel-lib/server.go @@ -70,6 +70,9 @@ type Server struct { // the domain of the server, used for validating clientIds domain string + // see ServerConfig.ValidateCertificate comment + validateCertificate func(domain string, request *http.Request) (identifier string, tenantId string, err error) + // yamuxConfig is passed to new yamux.Session's yamuxConfig *yamux.Config @@ -91,6 +94,15 @@ type ServerConfig struct { // the domain of the server, used for validating clientIds Domain string + // function that analyzes the TLS client certificate of the request. + // this is based on the CommonName attribute of the TLS certificate. + // If we are in multi-tenant mode, it must be formatted like `.@` + // otherwise, it must be formatted like `@` + // must match the configured Domain of this Threshold server + // the identifier it returns will be `.` or ``. + // the tenantId it returns will be `` or "" + ValidateCertificate func(domain string, request *http.Request) (identifier string, tenantId string, err error) + // YamuxConfig defines the config which passed to every new yamux.Session. If nil // yamux.DefaultConfig() is used. YamuxConfig *yamux.Config @@ -285,28 +297,13 @@ func (s *Server) dial(identifier string, service string) (net.Conn, error) { // controlHandler is used to capture incoming tunnel connect requests into raw // tunnel TCP connections. func (s *Server) controlHandler(w http.ResponseWriter, r *http.Request) (ctErr error) { - identifier := r.Header.Get(proto.ClientIdentifierHeader) - - // When TLS is turned on, the Client Authentication certificate is required, so in that case - // if we got to this point, we should make sure - // the ClientIdentifier header matches the CommonName on the client cert. - // https://stackoverflow.com/questions/31751764/get-remote-ssl-certificate-in-golang - if r.TLS != nil && len(r.TLS.PeerCertificates) > 0 { - cn := r.TLS.PeerCertificates[0].Subject.CommonName - if fmt.Sprintf("%s@%s", identifier, s.domain) != cn { - return fmt.Errorf( - "\"%s: %s\" does not match TLS certificate CommonName %s", - proto.ClientIdentifierHeader, identifier, cn, - ) - } - } - // We will allow clients to connect even if they are not configured to be used yet. - // In this case they have an empty set of listening front-end ports. - // ok := s.hasIdentifier(identifier) - // if !ok { - // return fmt.Errorf("no host associated for identifier %s. please use server.AddAddr()", identifier) - // } + clientId, tenantId, err := s.validateCertificate(s.domain, r) + fmt.Println(tenantId) + if err != nil { + return err + } + identifier := clientId ct, ok := s.getControl(identifier) if ok { @@ -613,7 +610,8 @@ func (s *Server) checkConnect(fn func(w http.ResponseWriter, r *http.Request) er if err := fn(w, r); err != nil { log.Printf("Server.checkConnect(): Handler err: %v\n", err.Error()) - if identifier := r.Header.Get(proto.ClientIdentifierHeader); identifier != "" { + identifier, _, err := s.validateCertificate(s.domain, r) + if err == nil { s.onDisconnect(identifier, err) } diff --git a/usage-example/client-config.json b/usage-example/client-config.json index 5587389..fff1666 100644 --- a/usage-example/client-config.json +++ b/usage-example/client-config.json @@ -2,7 +2,6 @@ "DebugLog": false, "ClientIdentifier": "TestClient1", "ServerAddr": "localhost:9056", - "UseTls": true, "ServiceToLocalAddrMap": { "fooService": "127.0.0.1:9001" }, diff --git a/usage-example/server-config.json b/usage-example/server-config.json index 8161b04..1e3ca17 100644 --- a/usage-example/server-config.json +++ b/usage-example/server-config.json @@ -3,7 +3,6 @@ "DebugLog": false, "Domain": "example.com", "ListenPort": 9056, - "UseTls": true, "CaCertificateFilesGlob": "InternalCA+chain.crt", "ServerTlsKeyFile": "localhost.key", "ServerTlsCertificateFile": "localhost+chain.crt" From b9b61e56d4ddf31481dc750cd9ff7875c5ffbccf Mon Sep 17 00:00:00 2001 From: forest Date: Thu, 17 Dec 2020 23:05:04 -0600 Subject: [PATCH 02/36] bandwidth metrics & prometheus metrics publisher --- README.md | 4 +- main.go | 317 ++++++++++++++++++++++++++++--- tunnel-lib/server.go | 107 ++++++++++- tunnel-lib/virtualaddr.go | 16 +- usage-example/client-config.json | 2 +- usage-example/tunnels.json | 2 +- 6 files changed, 405 insertions(+), 43 deletions(-) diff --git a/README.md b/README.md index e9535c6..fcd1a0a 100644 --- a/README.md +++ b/README.md @@ -47,7 +47,7 @@ Starting the tunnel client. Client Identifier: TestClient1 2020/08/06 14:00:04 theshold client is starting up using config: { "DebugLog": false, - "ClientIdentifier": "TestClient1", + "ClientId": "TestClient1", "ServerHost": "localhost", "ServerTunnelControlPort": 9056, "ServerManagementPort": 9057, @@ -67,7 +67,7 @@ Sending the tunnel configuration to the server. HTTP PUT localhost:9057/tunnels: now listening on 127.0.0.1:9000 -[{"HaProxyProxyProtocol":true,"ListenAddress":"127.0.0.1","ListenHostnameGlob":"*","ListenPort":9000,"BackEndService":"fooService","ClientIdentifier":"TestClient1"}] +[{"HaProxyProxyProtocol":true,"ListenAddress":"127.0.0.1","ListenHostnameGlob":"*","ListenPort":9000,"BackEndService":"fooService","ClientId":"TestClient1"}] Starting the "sender" test app. It connects to the front end port of the tunnel (port 9000). This would be your end user who wants to use the web application. diff --git a/main.go b/main.go index c98d92b..966ff38 100644 --- a/main.go +++ b/main.go @@ -5,7 +5,6 @@ import ( "crypto/tls" "crypto/x509" "encoding/json" - "errors" "flag" "fmt" "io" @@ -18,6 +17,7 @@ import ( "path" "path/filepath" "regexp" + "strconv" "strings" "sync" "time" @@ -45,22 +45,31 @@ type ServerConfig struct { // tenantId is N/A. ClientId must be formatted `` // clients can register listeners with any hostname including null, on any open port. // - MultiTenantMode bool + MultiTenantMode bool + MultiTenantInternalAPIListenPort int + MultiTenantInternalAPICaCertificateFile string CaCertificateFilesGlob string ServerTlsKeyFile string ServerTlsCertificateFile string + + Metrics MetricsConfig } type ClientConfig struct { DebugLog bool - ClientIdentifier string + ClientId string ServerAddr string ServiceToLocalAddrMap *map[string]string CaCertificateFilesGlob string ClientTlsKeyFile string ClientTlsCertificateFile string AdminUnixSocket string + Metrics MetricsConfig +} + +type MetricsConfig struct { + PrometheusMetricsAPIPort int } type ListenerConfig struct { @@ -69,7 +78,7 @@ type ListenerConfig struct { ListenHostnameGlob string ListenPort int BackEndService string - ClientIdentifier string + ClientId string } type ClientState struct { @@ -78,8 +87,29 @@ type ClientState struct { } type ManagementHttpHandler struct { - Domain string - ControlHandler http.Handler + Domain string + MultiTenantMode bool + ControlHandler http.Handler +} + +type BandwidthCounter struct { + Inbound int64 + Outbound int64 +} + +type MultiTenantInternalAPI struct{} + +type PrometheusMetricsAPI struct { + MultiTenantServerMode bool + InboundByTenant map[string]int64 + OutboundByTenant map[string]int64 + InboundByService map[string]int64 + OutboundByService map[string]int64 +} + +type Tenant struct { + ReservedPorts []int + AuthorizedDomains []string } type LiveConfigUpdate struct { @@ -92,7 +122,9 @@ type adminAPI struct{} // Server State var listenersByTenant map[string][]ListenerConfig var clientStatesMutex = &sync.Mutex{} +var tenantStatesMutex = &sync.Mutex{} var clientStatesByTenant map[string]map[string]ClientState +var tenants map[string]Tenant var server *tunnel.Server // Client State @@ -245,10 +277,10 @@ func runClient(configFileName *string) { )) } - if clientIdDomain[0] != config.ClientIdentifier { + if clientIdDomain[0] != config.ClientId { log.Fatal(fmt.Errorf( - "expected TLS client certificate common name clientId '%s' to match ClientIdentifier '%s'", - clientIdDomain[0], config.ClientIdentifier, + "expected TLS client certificate common name clientId '%s' to match ClientId '%s'", + clientIdDomain[0], config.ClientId, )) } @@ -279,13 +311,13 @@ func runClient(configFileName *string) { clientStateChanges := make(chan *tunnel.ClientStateChange) tunnelClientConfig := &tunnel.ClientConfig{ DebugLog: config.DebugLog, - Identifier: config.ClientIdentifier, + Identifier: config.ClientId, ServerAddr: config.ServerAddr, FetchLocalAddr: func(service string) (string, error) { //log.Printf("(*serviceToLocalAddrMap): %+v\n\n", (*serviceToLocalAddrMap)) localAddr, hasLocalAddr := (*serviceToLocalAddrMap)[service] if !hasLocalAddr { - return "", errors.New("service not configured. See ServiceToLocalAddrMap in client config file.") + return "", fmt.Errorf("service '%s' not configured. Set ServiceToLocalAddrMap in client config file or HTTP PUT /liveconfig over the AdminUnixSocket.", service) } return localAddr, nil }, @@ -340,7 +372,7 @@ func runClientAdminApi(config ClientConfig) { } } -func validateCertificate(domain string, request *http.Request) (identifier string, tenantId string, err error) { +func validateCertificate(domain string, multiTenantMode bool, request *http.Request) (identifier string, tenantId string, err error) { if len(request.TLS.PeerCertificates) != 1 { return "", "", fmt.Errorf("expected exactly 1 TLS client certificate, got %d", len(request.TLS.PeerCertificates)) } @@ -361,7 +393,7 @@ func validateCertificate(domain string, request *http.Request) (identifier strin identifier = clientIdDomain[0] nodeId := identifier - if strings.Contains(identifier, ".") { + if multiTenantMode { tenantIdNodeId := strings.Split(identifier, ".") if len(tenantIdNodeId) != 2 { return "", "", fmt.Errorf( @@ -400,9 +432,18 @@ func runServer(configFileName *string) { clientStateChangeChannel := make(chan *tunnel.ClientStateChange) + var metricChannel chan tunnel.BandwidthMetric = nil + + // the Server should only collect metrics when in multi-tenant mode -- this is needed for billing + if config.MultiTenantMode { + metricChannel = make(chan tunnel.BandwidthMetric) + go exportMetrics(config.Metrics /*multiTenantServerMode: */, true, metricChannel) + } + tunnelServerConfig := &tunnel.ServerConfig{ StateChanges: clientStateChangeChannel, ValidateCertificate: validateCertificate, + Bandwidth: metricChannel, Domain: config.Domain, DebugLog: config.DebugLog, } @@ -416,11 +457,10 @@ func runServer(configFileName *string) { go (func() { for { clientStateChange := <-clientStateChangeChannel - clientStatesMutex.Lock() previousState := "" currentState := clientStateChange.Current.String() tenantId := "" - if strings.Contains(clientStateChange.Identifier, ".") { + if config.MultiTenantMode { tenantIdNodeId := strings.Split(clientStateChange.Identifier, ".") if len(tenantIdNodeId) != 2 { fmt.Printf("runServer(): go func(): can't handle clientStateChange with malformed Identifier '%s' \n", clientStateChange.Identifier) @@ -429,6 +469,7 @@ func runServer(configFileName *string) { tenantId = tenantIdNodeId[0] } + clientStatesMutex.Lock() if _, hasTenant := clientStatesByTenant[tenantId]; !hasTenant { clientStatesByTenant[tenantId] = map[string]ClientState{} } @@ -466,6 +507,7 @@ func runServer(configFileName *string) { } tlsConfig := &tls.Config{ + ClientCAs: caCertPool, ClientAuth: tls.RequireAndVerifyClientCert, } @@ -475,11 +517,37 @@ func runServer(configFileName *string) { Addr: fmt.Sprintf(":%d", config.ListenPort), TLSConfig: tlsConfig, Handler: &(ManagementHttpHandler{ - Domain: config.Domain, - ControlHandler: server, + Domain: config.Domain, + MultiTenantMode: config.MultiTenantMode, + ControlHandler: server, }), } + if config.MultiTenantMode { + go (func() { + caCertPool := x509.NewCertPool() + caCert, err := ioutil.ReadFile(config.MultiTenantInternalAPICaCertificateFile) + if err != nil { + log.Fatal(err) + } + caCertPool.AppendCertsFromPEM(caCert) + tlsConfig := &tls.Config{ + ClientCAs: caCertPool, + ClientAuth: tls.RequireAndVerifyClientCert, + } + tlsConfig.BuildNameToCertificate() + + multiTenantInternalServer := &http.Server{ + Addr: fmt.Sprintf(":%d", config.MultiTenantInternalAPIListenPort), + TLSConfig: tlsConfig, + Handler: &MultiTenantInternalAPI{}, + } + + err = multiTenantInternalServer.ListenAndServeTLS(config.ServerTlsCertificateFile, config.ServerTlsKeyFile) + panic(err) + })() + } + log.Print("runServer(): the server should be running now\n") err = httpsManagementServer.ListenAndServeTLS(config.ServerTlsCertificateFile, config.ServerTlsKeyFile) panic(err) @@ -491,12 +559,12 @@ func setListeners(tenantId string, listenerConfigs []ListenerConfig) (int, strin newListenersThatHaveToBeAdded := make([]ListenerConfig, 0) for _, newListenerConfig := range listenerConfigs { - clientState, everHeardOfClientBefore := clientStatesByTenant[tenantId][newListenerConfig.ClientIdentifier] + clientState, everHeardOfClientBefore := clientStatesByTenant[tenantId][newListenerConfig.ClientId] if !everHeardOfClientBefore { - return http.StatusNotFound, fmt.Sprintf("Client %s Not Found", newListenerConfig.ClientIdentifier) + return http.StatusNotFound, fmt.Sprintf("Client %s Not Found", newListenerConfig.ClientId) } if clientState.CurrentState != tunnel.ClientConnected.String() { - return http.StatusNotFound, fmt.Sprintf("Client %s is not connected it is %s", newListenerConfig.ClientIdentifier, clientState.CurrentState) + return http.StatusNotFound, fmt.Sprintf("Client %s is not connected it is %s", newListenerConfig.ClientId, clientState.CurrentState) } } @@ -539,14 +607,14 @@ func setListeners(tenantId string, listenerConfigs []ListenerConfig) (int, strin listenAddress, newListenerConfig.ListenPort, newListenerConfig.ListenHostnameGlob, - newListenerConfig.ClientIdentifier, + newListenerConfig.ClientId, newListenerConfig.HaProxyProxyProtocol, newListenerConfig.BackEndService, ) if err != nil { if strings.Contains(err.Error(), "already in use") { - return http.StatusConflict, fmt.Sprintf("Port Conflict Port %s already in use", listenAddress) + return http.StatusConflict, fmt.Sprintf("Port Conflict: Port %s is reserved or already in use", listenAddress) } log.Printf("setListeners(): can't net.Listen(\"tcp\", \"%s\") because %s \n", listenAddress, err) @@ -563,18 +631,138 @@ func setListeners(tenantId string, listenerConfigs []ListenerConfig) (int, strin } +func exportMetrics(config MetricsConfig, multiTenantServerMode bool, bandwidth <-chan tunnel.BandwidthMetric) { + metricsAPI := &PrometheusMetricsAPI{ + MultiTenantServerMode: multiTenantServerMode, + InboundByTenant: map[string]int64{}, + OutboundByTenant: map[string]int64{}, + InboundByService: map[string]int64{}, + OutboundByService: map[string]int64{}, + } + + go (func() { + for { + metric := <-bandwidth + if multiTenantServerMode { + tenantIdNodeId := strings.Split(metric.ClientId, ".") + if len(tenantIdNodeId) != 2 { + panic(fmt.Errorf("malformed metric.ClientId '%s', expected .", metric.ClientId)) + } + if metric.Inbound { + metricsAPI.InboundByTenant[tenantIdNodeId[0]] += int64(metric.Bytes) + } else { + metricsAPI.OutboundByTenant[tenantIdNodeId[0]] += int64(metric.Bytes) + } + } else { + if metric.Inbound { + metricsAPI.InboundByService[metric.Service] += int64(metric.Bytes) + } else { + metricsAPI.OutboundByService[metric.Service] += int64(metric.Bytes) + } + } + } + })() + + go (func() { + metricsServer := &http.Server{ + Addr: fmt.Sprintf(":%d", config.PrometheusMetricsAPIPort), + Handler: metricsAPI, + } + err := metricsServer.ListenAndServe() + panic(err) + })() +} + +func (s *PrometheusMetricsAPI) ServeHTTP(responseWriter http.ResponseWriter, request *http.Request) { + + getMillisecondsSinceUnixEpoch := func() int64 { + return time.Now().UnixNano() / int64(time.Millisecond) + } + + responseWriter.Header().Set("Content-Type", "text/plain; version=0.0.4") + + writeMetric := func(inbound map[string]int64, outbound map[string]int64, name, tag, desc string) { + timestamp := getMillisecondsSinceUnixEpoch() + responseWriter.Write([]byte(fmt.Sprintf("# HELP %s %s\n", name, desc))) + responseWriter.Write([]byte(fmt.Sprintf("# TYPE %s counter\n", name))) + for id, bytes := range inbound { + responseWriter.Write([]byte(fmt.Sprintf("%s{%s=\"%s\",direction=\"inbound\"} %d %d\n", name, tag, id, bytes, timestamp))) + } + for id, bytes := range outbound { + responseWriter.Write([]byte(fmt.Sprintf("%s{%s=\"%s\",direction=\"outbound\"} %d %d\n", name, tag, id, bytes, timestamp))) + } + } + + if s.MultiTenantServerMode { + writeMetric(s.InboundByTenant, s.OutboundByTenant, "bandwidth_by_tenant", "tenant", "bandwidth usage by tenant in bytes, excluding usage from control protocol.") + } else { + writeMetric(s.InboundByService, s.OutboundByService, "bandwidth_by_service", "service", "bandwidth usage by service in bytes.") + } +} + func compareListenerConfigs(a, b ListenerConfig) bool { return (a.ListenPort == b.ListenPort && a.ListenAddress == b.ListenAddress && a.ListenHostnameGlob == b.ListenHostnameGlob && a.BackEndService == b.BackEndService && - a.ClientIdentifier == b.ClientIdentifier && + a.ClientId == b.ClientId && a.HaProxyProxyProtocol == b.HaProxyProxyProtocol) } +func (s *MultiTenantInternalAPI) ServeHTTP(responseWriter http.ResponseWriter, request *http.Request) { + switch path.Clean(request.URL.Path) { + case "/tenants": + if request.Method == "GET" || request.Method == "PUT" { + if request.Method == "PUT" { + if request.Header.Get("Content-Type") != "application/json" { + http.Error(responseWriter, "415 Unsupported Media Type: Content-Type must be application/json", http.StatusUnsupportedMediaType) + } else { + bodyBytes, err := ioutil.ReadAll(request.Body) + if err != nil { + http.Error(responseWriter, "500 Read Error", http.StatusInternalServerError) + return + } + var newTenants map[string]Tenant + err = json.Unmarshal(bodyBytes, &newTenants) + if err != nil { + http.Error(responseWriter, "422 Unprocessable Entity: Can't Parse JSON", http.StatusUnprocessableEntity) + return + } + tenantStatesMutex.Lock() + tenants = newTenants + tenantStatesMutex.Unlock() + } + } + + tenantStatesMutex.Lock() + bytes, err := json.Marshal(tenants) + tenantStatesMutex.Unlock() + if err != nil { + http.Error(responseWriter, "500 JSON Marshal Error", http.StatusInternalServerError) + return + } + responseWriter.Header().Set("Content-Type", "application/json") + responseWriter.Write(bytes) + + } else { + responseWriter.Header().Set("Allow", "GET, PUT") + http.Error(responseWriter, "405 Method Not Allowed, try GET or PUT", http.StatusMethodNotAllowed) + } + case "/ping": + if request.Method == "GET" { + fmt.Fprint(responseWriter, "pong") + } else { + responseWriter.Header().Set("Allow", "GET") + http.Error(responseWriter, "405 method not allowed, try GET", http.StatusMethodNotAllowed) + } + default: + http.Error(responseWriter, "404 Not Found, try /tenants or /ping", http.StatusNotFound) + } +} + func (s *ManagementHttpHandler) ServeHTTP(responseWriter http.ResponseWriter, request *http.Request) { - _, tenantId, err := validateCertificate(s.Domain, request) + _, tenantId, err := validateCertificate(s.Domain, s.MultiTenantMode, request) if err != nil { http.Error(responseWriter, fmt.Sprintf("400 bad request: %s", err.Error()), http.StatusBadRequest) return @@ -621,6 +809,71 @@ func (s *ManagementHttpHandler) ServeHTTP(responseWriter http.ResponseWriter, re return } + if s.MultiTenantMode { + for _, listenerConfig := range listenerConfigs { + tenantIdNodeId := strings.Split(listenerConfig.ClientId, ".") + if len(tenantIdNodeId) != 2 { + http.Error( + responseWriter, + fmt.Sprintf( + "400 Bad Request: invalid ClientId '%s'. It needs to be in the form '.'", + listenerConfig.ClientId, + ), + http.StatusBadRequest, + ) + return + } + tenant, hasTenant := tenants[tenantIdNodeId[0]] + if !hasTenant { + http.Error( + responseWriter, + fmt.Sprintf("400 Bad Request: unknown tenantId '%s'", tenantIdNodeId[0]), + http.StatusBadRequest, + ) + } + isAuthorizedDomain := false + for _, tenantAuthorizedDomain := range tenant.AuthorizedDomains { + isSubdomain := strings.HasSuffix(listenerConfig.ListenHostnameGlob, fmt.Sprintf(".%s", tenantAuthorizedDomain)) + if (tenantAuthorizedDomain == listenerConfig.ListenHostnameGlob) || isSubdomain { + isAuthorizedDomain = true + break + } + } + if listenerConfig.ListenHostnameGlob != "" && !isAuthorizedDomain { + http.Error( + responseWriter, + fmt.Sprintf( + "400 Bad Request: ListenHostnameGlob '%s' is not covered by any of your authorized domains [%s]", + listenerConfig.ListenHostnameGlob, + strings.Join(stringSliceMap(tenant.AuthorizedDomains, func(x string) string { return fmt.Sprintf("'%s'", x) }), ", "), + ), + http.StatusBadRequest, + ) + } + + if listenerConfig.ListenHostnameGlob == "" { + isReservedPort := false + for _, tenantReservedPort := range tenant.ReservedPorts { + if listenerConfig.ListenPort == tenantReservedPort { + isReservedPort = true + break + } + } + if !isReservedPort { + http.Error( + responseWriter, + fmt.Sprintf( + "400 Bad Request: ListenHostnameGlob is empty and ListenPort '%d' is not one of your reserved ports [%s]", + listenerConfig.ListenPort, + strings.Join(intSlice2StringSlice(tenant.ReservedPorts), ", "), + ), + http.StatusBadRequest, + ) + } + } + } + } + statusCode, errorMessage := setListeners(tenantId, listenerConfigs) if statusCode != 200 { @@ -667,3 +920,19 @@ func getConfigBytes(configFileName *string) []byte { return nil } } + +func intSlice2StringSlice(slice []int) []string { + toReturn := make([]string, len(slice)) + for i, integer := range slice { + toReturn[i] = strconv.Itoa(integer) + } + return toReturn +} + +func stringSliceMap(slice []string, mapper func(string) string) []string { + toReturn := make([]string, len(slice)) + for i, str := range slice { + toReturn[i] = mapper(str) + } + return toReturn +} diff --git a/tunnel-lib/server.go b/tunnel-lib/server.go index 6936672..58f2fdf 100644 --- a/tunnel-lib/server.go +++ b/tunnel-lib/server.go @@ -24,6 +24,7 @@ import ( var ( errNoClientSession = errors.New("no client session established") defaultTimeout = 10 * time.Second + metricChunkSize = 1000000 // one megabyte ) // Server is responsible for proxying public connections to the client over a @@ -70,6 +71,8 @@ type Server struct { // the domain of the server, used for validating clientIds domain string + bandwidth chan<- BandwidthMetric + // see ServerConfig.ValidateCertificate comment validateCertificate func(domain string, request *http.Request) (identifier string, tenantId string, err error) @@ -79,6 +82,14 @@ type Server struct { debugLog bool } +type BandwidthMetric struct { + Bytes int + RemoteAddress net.Addr + Inbound bool + Service string + ClientId string +} + // ServerConfig defines the configuration for the Server type ServerConfig struct { // StateChanges receives state transition details each time client @@ -94,6 +105,8 @@ type ServerConfig struct { // the domain of the server, used for validating clientIds Domain string + Bandwidth chan<- BandwidthMetric + // function that analyzes the TLS client certificate of the request. // this is based on the CommonName attribute of the TLS certificate. // If we are in multi-tenant mode, it must be formatted like `.@` @@ -101,7 +114,7 @@ type ServerConfig struct { // must match the configured Domain of this Threshold server // the identifier it returns will be `.` or ``. // the tenantId it returns will be `` or "" - ValidateCertificate func(domain string, request *http.Request) (identifier string, tenantId string, err error) + ValidateCertificate func(domain string, multiTenantMode bool, request *http.Request) (identifier string, tenantId string, err error) // YamuxConfig defines the config which passed to every new yamux.Session. If nil // yamux.DefaultConfig() is used. @@ -133,6 +146,7 @@ func NewServer(cfg *ServerConfig) (*Server, error) { virtualAddrs: newVirtualAddrs(opts), controls: newControls(), states: make(map[string]ClientState), + bandwidth: cfg.Bandwidth, stateCh: cfg.StateChanges, domain: cfg.Domain, yamuxConfig: yamuxConfig, @@ -191,11 +205,11 @@ func (s *Server) handleTCPConn(conn net.Conn) error { return err } - service := strconv.Itoa(port) + service := fmt.Sprintf("port%d", port) if listenerInfo.BackendService != "" { service = listenerInfo.BackendService } - stream, err := s.dial(listenerInfo.AssociatedClientIdentity, service) + stream, err := s.dial(listenerInfo.AssociatedClientId, service) if err != nil { return err } @@ -223,8 +237,21 @@ func (s *Server) handleTCPConn(conn net.Conn) error { disconnectedChan := make(chan bool) - go s.proxy(disconnectedChan, conn, stream, "from proxy-client to client") - go s.proxy(disconnectedChan, stream, conn, "from client to proxy-client") + inboundMetric := BandwidthMetric{ + Service: listenerInfo.BackendService, + ClientId: listenerInfo.AssociatedClientId, + RemoteAddress: conn.RemoteAddr(), + Inbound: true, + } + outboundMetric := BandwidthMetric{ + Service: listenerInfo.BackendService, + ClientId: listenerInfo.AssociatedClientId, + RemoteAddress: conn.RemoteAddr(), + Inbound: false, + } + + go s.proxy(disconnectedChan, conn, stream, outboundMetric, s.bandwidth, "outbound from tunnel to remote client") + go s.proxy(disconnectedChan, stream, conn, inboundMetric, s.bandwidth, "inbound from remote client to tunnel") // Once one member of this conversation has disconnected, we should end the conversation for all parties. <-disconnectedChan @@ -232,18 +259,84 @@ func (s *Server) handleTCPConn(conn net.Conn) error { return nonil(stream.Close(), conn.Close()) } -func (s *Server) proxy(disconnectedChan chan bool, dst, src net.Conn, side string) { +func (s *Server) proxy(disconnectedChan chan bool, dst, src net.Conn, metric BandwidthMetric, bandwidth chan<- BandwidthMetric, side string) { defer (func() { disconnectedChan <- true })() if s.debugLog { log.Printf("Server.proxy(): tunneling %s -> %s (%s)\n", src.RemoteAddr(), dst.RemoteAddr(), side) } - n, err := io.Copy(dst, src) + var n int64 + var err error + if bandwidth != nil { + n, err = ioCopyWithMetrics(dst, src, metric, bandwidth) + } else { + n, err = io.Copy(dst, src) + } + if s.debugLog { log.Printf("Server.proxy(): tunneled %d bytes %s -> %s (%s): %v\n", n, src.RemoteAddr(), dst.RemoteAddr(), side, err) } } +// copied from the go standard library source code (io.Copy) with metric collection added. +func ioCopyWithMetrics(dst io.Writer, src io.Reader, metric BandwidthMetric, bandwidth chan<- BandwidthMetric) (written int64, err error) { + size := 32 * 1024 + if l, ok := src.(*io.LimitedReader); ok && int64(size) > l.N { + if l.N < 1 { + size = 1 + } else { + size = int(l.N) + } + } + chunkForMetrics := 0 + buf := make([]byte, size) + + for { + nr, er := src.Read(buf) + if nr > 0 { + nw, ew := dst.Write(buf[0:nr]) + if nw > 0 { + chunkForMetrics += nw + if chunkForMetrics >= metricChunkSize { + bandwidth <- BandwidthMetric{ + Inbound: metric.Inbound, + Service: metric.Service, + ClientId: metric.ClientId, + RemoteAddress: metric.RemoteAddress, + Bytes: chunkForMetrics, + } + chunkForMetrics = 0 + } + written += int64(nw) + } + if ew != nil { + err = ew + break + } + if nr != nw { + err = io.ErrShortWrite + break + } + } + if er != nil { + if er != io.EOF { + err = er + } + break + } + } + if chunkForMetrics > 0 { + bandwidth <- BandwidthMetric{ + Inbound: metric.Inbound, + Service: metric.Service, + ClientId: metric.ClientId, + RemoteAddress: metric.RemoteAddress, + Bytes: chunkForMetrics, + } + } + return written, err +} + func (s *Server) dial(identifier string, service string) (net.Conn, error) { control, ok := s.getControl(identifier) if !ok { diff --git a/tunnel-lib/virtualaddr.go b/tunnel-lib/virtualaddr.go index 8fd0a51..f6626ed 100644 --- a/tunnel-lib/virtualaddr.go +++ b/tunnel-lib/virtualaddr.go @@ -16,9 +16,9 @@ type ListenerInfo struct { //Send the HAProxy PROXY protocol v1 header to the proxy client before streaming TCP from the remote client. SendProxyProtocolv1 bool - BackendService string - AssociatedClientIdentity string - HostnameGlob string + BackendService string + AssociatedClientId string + HostnameGlob string } type listener struct { @@ -142,10 +142,10 @@ func (vaddr *vaddrStorage) Add(ip net.IP, port int, hostnameGlob string, ident s func (l *listener) addHost(hostnameGlob string, ident string, sendProxyProtocolv1 bool, service string) { l.backends = append(l.backends, ListenerInfo{ - HostnameGlob: hostnameGlob, - AssociatedClientIdentity: ident, - SendProxyProtocolv1: sendProxyProtocolv1, - BackendService: service, + HostnameGlob: hostnameGlob, + AssociatedClientId: ident, + SendProxyProtocolv1: sendProxyProtocolv1, + BackendService: service, }) } @@ -217,7 +217,7 @@ func (vaddr *vaddrStorage) newListener(ip net.IP, port int) (*listener, error) { func (vaddr *vaddrStorage) HasIdentifier(identifier string) bool { for _, listener := range vaddr.listeners { for _, backend := range listener.backends { - if backend.AssociatedClientIdentity == identifier { + if backend.AssociatedClientId == identifier { return true } } diff --git a/usage-example/client-config.json b/usage-example/client-config.json index fff1666..1d981b6 100644 --- a/usage-example/client-config.json +++ b/usage-example/client-config.json @@ -1,6 +1,6 @@ { "DebugLog": false, - "ClientIdentifier": "TestClient1", + "ClientId": "TestClient1", "ServerAddr": "localhost:9056", "ServiceToLocalAddrMap": { "fooService": "127.0.0.1:9001" diff --git a/usage-example/tunnels.json b/usage-example/tunnels.json index 87c24a0..5949381 100644 --- a/usage-example/tunnels.json +++ b/usage-example/tunnels.json @@ -1,6 +1,6 @@ [ { - "ClientIdentifier": "TestClient1", + "ClientId": "TestClient1", "ListenPort": 9000, "ListenAddress": "127.0.0.1", "ListenHostnameGlob": "*", From 4e66a4a7238c2a9d0e7e85f7b328846489ba3bca Mon Sep 17 00:00:00 2001 From: forest Date: Thu, 17 Dec 2020 23:25:03 -0600 Subject: [PATCH 03/36] support JSON metrics --- main.go | 43 ++++++++++++++++++++++++++++++++++--------- 1 file changed, 34 insertions(+), 9 deletions(-) diff --git a/main.go b/main.go index 966ff38..b32ca91 100644 --- a/main.go +++ b/main.go @@ -679,24 +679,49 @@ func (s *PrometheusMetricsAPI) ServeHTTP(responseWriter http.ResponseWriter, req return time.Now().UnixNano() / int64(time.Millisecond) } - responseWriter.Header().Set("Content-Type", "text/plain; version=0.0.4") - writeMetric := func(inbound map[string]int64, outbound map[string]int64, name, tag, desc string) { timestamp := getMillisecondsSinceUnixEpoch() responseWriter.Write([]byte(fmt.Sprintf("# HELP %s %s\n", name, desc))) responseWriter.Write([]byte(fmt.Sprintf("# TYPE %s counter\n", name))) - for id, bytes := range inbound { - responseWriter.Write([]byte(fmt.Sprintf("%s{%s=\"%s\",direction=\"inbound\"} %d %d\n", name, tag, id, bytes, timestamp))) + for id, bytez := range inbound { + responseWriter.Write([]byte(fmt.Sprintf("%s{%s=\"%s\",direction=\"inbound\"} %d %d\n", name, tag, id, bytez, timestamp))) } - for id, bytes := range outbound { - responseWriter.Write([]byte(fmt.Sprintf("%s{%s=\"%s\",direction=\"outbound\"} %d %d\n", name, tag, id, bytes, timestamp))) + for id, bytez := range outbound { + responseWriter.Write([]byte(fmt.Sprintf("%s{%s=\"%s\",direction=\"outbound\"} %d %d\n", name, tag, id, bytez, timestamp))) } } - if s.MultiTenantServerMode { - writeMetric(s.InboundByTenant, s.OutboundByTenant, "bandwidth_by_tenant", "tenant", "bandwidth usage by tenant in bytes, excluding usage from control protocol.") + if strings.Contains(request.Header.Get("Accept"), "application/json") { + var bytez []byte + var err error + if s.MultiTenantServerMode { + bytez, err = json.MarshalIndent(PrometheusMetricsAPI{ + InboundByTenant: s.InboundByTenant, + OutboundByTenant: s.OutboundByTenant, + }, "", " ") + } else { + bytez, err = json.MarshalIndent(PrometheusMetricsAPI{ + InboundByService: s.InboundByService, + OutboundByService: s.OutboundByService, + }, "", " ") + } + + if err != nil { + log.Printf(fmt.Sprintf("500 internal server error: %s", err)) + http.Error(responseWriter, "500 internal server error", http.StatusInternalServerError) + return + } + + responseWriter.Header().Set("Content-Type", "application/json") + responseWriter.Write(bytez) } else { - writeMetric(s.InboundByService, s.OutboundByService, "bandwidth_by_service", "service", "bandwidth usage by service in bytes.") + responseWriter.Header().Set("Content-Type", "text/plain; version=0.0.4") + + if s.MultiTenantServerMode { + writeMetric(s.InboundByTenant, s.OutboundByTenant, "bandwidth_by_tenant", "tenant", "bandwidth usage by tenant in bytes, excluding usage from control protocol.") + } else { + writeMetric(s.InboundByService, s.OutboundByService, "bandwidth_by_service", "service", "bandwidth usage by service in bytes.") + } } } From 4865eadad8165c2e1681c4895fc28c570ebd80af Mon Sep 17 00:00:00 2001 From: forest Date: Tue, 19 Jan 2021 19:24:16 -0600 Subject: [PATCH 04/36] add support for multiple servers per client --- main.go | 190 +++++++++++++++++++++++++++++++++----------------------- 1 file changed, 113 insertions(+), 77 deletions(-) diff --git a/main.go b/main.go index b32ca91..02e68ef 100644 --- a/main.go +++ b/main.go @@ -27,7 +27,7 @@ import ( type ServerConfig struct { DebugLog bool - ListenPort int + ListenPort int // default 9056 // Domain is only used for validating the TLS client certificates // when TLS is used. the cert's Subject CommonName is expected to be @ @@ -46,7 +46,7 @@ type ServerConfig struct { // clients can register listeners with any hostname including null, on any open port. // MultiTenantMode bool - MultiTenantInternalAPIListenPort int + MultiTenantInternalAPIListenPort int // default 9057 MultiTenantInternalAPICaCertificateFile string CaCertificateFilesGlob string @@ -60,6 +60,7 @@ type ClientConfig struct { DebugLog bool ClientId string ServerAddr string + Servers []string ServiceToLocalAddrMap *map[string]string CaCertificateFilesGlob string ClientTlsKeyFile string @@ -68,6 +69,12 @@ type ClientConfig struct { Metrics MetricsConfig } +type ClientServer struct { + Client *tunnel.Client + ServerUrl *url.URL + ServerHostPort string +} + type MetricsConfig struct { PrometheusMetricsAPIPort int } @@ -128,9 +135,8 @@ var tenants map[string]Tenant var server *tunnel.Server // Client State -var client *tunnel.Client +var servers []ClientServer var tlsClientConfig *tls.Config -var serverHostPort *string var serviceToLocalAddrMap *map[string]string func main() { @@ -177,52 +183,56 @@ func (handler adminAPI) ServeHTTP(response http.ResponseWriter, request *http.Re http.Error(response, "500 Listeners json serialization failed", http.StatusInternalServerError) return } - apiURL := fmt.Sprintf("https://%s/tunnels", *serverHostPort) - tunnelsRequest, err := http.NewRequest("PUT", apiURL, bytes.NewReader(sendBytes)) - if err != nil { - log.Printf("adminAPI: error creating tunnels request: %+v\n\n", err) - http.Error(response, "500 error creating tunnels request", http.StatusInternalServerError) - return - } - tunnelsRequest.Header.Add("content-type", "application/json") - client := &http.Client{ Transport: &http.Transport{ TLSClientConfig: tlsClientConfig, }, Timeout: 10 * time.Second, } - tunnelsResponse, err := client.Do(tunnelsRequest) - if err != nil { - log.Printf("adminAPI: Do(tunnelsRequest): %+v\n\n", err) - http.Error(response, "502 tunnels request failed", http.StatusBadGateway) - return - } - tunnelsResponseBytes, err := ioutil.ReadAll(tunnelsResponse.Body) - if err != nil { - log.Printf("adminAPI: tunnelsResponse read error: %+v\n\n", err) - http.Error(response, "502 tunnelsResponse read error", http.StatusBadGateway) - return - } - if tunnelsResponse.StatusCode != http.StatusOK { - log.Printf( - "adminAPI: tunnelsRequest returned HTTP %d: %s\n\n", - tunnelsResponse.StatusCode, string(tunnelsResponseBytes), - ) - http.Error( - response, - fmt.Sprintf("502 tunnels request returned HTTP %d", tunnelsResponse.StatusCode), - http.StatusBadGateway, - ) - return + // TODO make this concurrent requests, not one by one. + for _, server := range servers { + apiURL := fmt.Sprintf("https://%s/tunnels", server.ServerHostPort) + tunnelsRequest, err := http.NewRequest("PUT", apiURL, bytes.NewReader(sendBytes)) + if err != nil { + log.Printf("adminAPI: error creating tunnels request: %+v\n\n", err) + http.Error(response, "500 error creating tunnels request", http.StatusInternalServerError) + return + } + tunnelsRequest.Header.Add("content-type", "application/json") + + tunnelsResponse, err := client.Do(tunnelsRequest) + if err != nil { + log.Printf("adminAPI: Do(tunnelsRequest): %+v\n\n", err) + http.Error(response, "502 tunnels request failed", http.StatusBadGateway) + return + } + tunnelsResponseBytes, err := ioutil.ReadAll(tunnelsResponse.Body) + if err != nil { + log.Printf("adminAPI: tunnelsResponse read error: %+v\n\n", err) + http.Error(response, "502 tunnelsResponse read error", http.StatusBadGateway) + return + } + + if tunnelsResponse.StatusCode != http.StatusOK { + log.Printf( + "adminAPI: tunnelsRequest returned HTTP %d: %s\n\n", + tunnelsResponse.StatusCode, string(tunnelsResponseBytes), + ) + http.Error( + response, + fmt.Sprintf("502 tunnels request returned HTTP %d", tunnelsResponse.StatusCode), + http.StatusBadGateway, + ) + return + } } serviceToLocalAddrMap = &configUpdate.ServiceToLocalAddrMap response.Header().Add("content-type", "application/json") response.WriteHeader(http.StatusOK) - response.Write(tunnelsResponseBytes) + response.Write(requestBytes) } else { response.Header().Set("Allow", "PUT") @@ -244,14 +254,32 @@ func runClient(configFileName *string) { log.Fatalf("runClient(): can't json.Unmarshal(configBytes, &config) because %s \n", err) } - serviceToLocalAddrMap = config.ServiceToLocalAddrMap - serverHostPort = &config.ServerAddr - serverURLString := fmt.Sprintf("https://%s", *serverHostPort) - serverURL, err := url.Parse(serverURLString) - if err != nil { - log.Fatal(fmt.Errorf("failed to parse the ServerAddr (prefixed with https://) '%s' as a url", serverURLString)) + servers := []ClientServer{} + makeServer := func(hostPort string) ClientServer { + serverURLString := fmt.Sprintf("https://%s", hostPort) + serverURL, err := url.Parse(serverURLString) + if err != nil { + log.Fatal(fmt.Errorf("failed to parse the ServerAddr (prefixed with https://) '%s' as a url", serverURLString)) + } + return ClientServer{ + ServerHostPort: hostPort, + ServerUrl: serverURL, + } + } + + if config.Servers != nil && len(config.Servers) > 0 { + if config.ServerAddr != "" { + log.Fatal("config contains both Servers and ServerAddr, only use one or the other") + } + for _, serverHostPort := range config.Servers { + servers = append(servers, makeServer(serverHostPort)) + } + } else { + servers = []ClientServer{makeServer(config.ServerAddr)} } + serviceToLocalAddrMap = config.ServiceToLocalAddrMap + configToLog, _ := json.MarshalIndent(config, "", " ") log.Printf("theshold client is starting up using config:\n%s\n", string(configToLog)) @@ -270,12 +298,15 @@ func runClient(configFileName *string) { "expected TLS client certificate common name '%s' to match format '@'", commonName, )) } - if clientIdDomain[1] != serverURL.Hostname() { - log.Fatal(fmt.Errorf( - "expected TLS client certificate common name domain '%s' to match ServerAddr domain '%s'", - clientIdDomain[1], serverURL.Hostname(), - )) - } + + // This is enforced by the server anyways, so no need to enforce it here. + // This allows server URLs to use IP addresses, don't require DNS. + // if clientIdDomain[1] != serverURL.Hostname() { + // log.Fatal(fmt.Errorf( + // "expected TLS client certificate common name domain '%s' to match ServerAddr domain '%s'", + // clientIdDomain[1], serverURL.Hostname(), + // )) + // } if clientIdDomain[0] != config.ClientId { log.Fatal(fmt.Errorf( @@ -308,40 +339,45 @@ func runClient(configFileName *string) { return tls.Dial(network, address, tlsClientConfig) } - clientStateChanges := make(chan *tunnel.ClientStateChange) - tunnelClientConfig := &tunnel.ClientConfig{ - DebugLog: config.DebugLog, - Identifier: config.ClientId, - ServerAddr: config.ServerAddr, - FetchLocalAddr: func(service string) (string, error) { - //log.Printf("(*serviceToLocalAddrMap): %+v\n\n", (*serviceToLocalAddrMap)) - localAddr, hasLocalAddr := (*serviceToLocalAddrMap)[service] - if !hasLocalAddr { - return "", fmt.Errorf("service '%s' not configured. Set ServiceToLocalAddrMap in client config file or HTTP PUT /liveconfig over the AdminUnixSocket.", service) - } - return localAddr, nil - }, - Dial: dialFunction, - StateChanges: clientStateChanges, - } + go runClientAdminApi(config) - client, err = tunnel.NewClient(tunnelClientConfig) - if err != nil { - log.Fatalf("runClient(): can't create tunnel client because %s \n", err) - } + fetchLocalAddr := func(service string) (string, error) { + //log.Printf("(*serviceToLocalAddrMap): %+v\n\n", (*serviceToLocalAddrMap)) + localAddr, hasLocalAddr := (*serviceToLocalAddrMap)[service] + if !hasLocalAddr { + return "", fmt.Errorf("service '%s' not configured. Set ServiceToLocalAddrMap in client config file or HTTP PUT /liveconfig over the AdminUnixSocket.", service) + } + return localAddr, nil + } + + for _, server := range servers { + clientStateChanges := make(chan *tunnel.ClientStateChange) + tunnelClientConfig := &tunnel.ClientConfig{ + DebugLog: config.DebugLog, + Identifier: config.ClientId, + ServerAddr: server.ServerHostPort, + FetchLocalAddr: fetchLocalAddr, + Dial: dialFunction, + StateChanges: clientStateChanges, + } - go (func() { - for { - stateChange := <-clientStateChanges - fmt.Printf("clientStateChange: %s\n", stateChange.String()) + client, err := tunnel.NewClient(tunnelClientConfig) + if err != nil { + log.Fatalf("runClient(): can't create tunnel client for %s because %v \n", server.ServerHostPort, err) } - })() - go runClientAdminApi(config) + go (func() { + for { + stateChange := <-clientStateChanges + log.Printf("%s clientStateChange: %s\n", server.ServerHostPort, stateChange.String()) + } + })() - fmt.Print("runClient(): the client should be running now\n") - client.Start() + server.Client = client + go server.Client.Start() + } + log.Print("runClient(): the client should be running now\n") } func runClientAdminApi(config ClientConfig) { From 6d225f9a35b40cdefe487d6f8341c87d7cc60264 Mon Sep 17 00:00:00 2001 From: forest Date: Tue, 19 Jan 2021 21:28:12 -0600 Subject: [PATCH 05/36] split client and server into separate files :D --- main.go | 926 ------------------------------------------------- main_client.go | 312 +++++++++++++++++ main_server.go | 651 ++++++++++++++++++++++++++++++++++ 3 files changed, 963 insertions(+), 926 deletions(-) create mode 100644 main_client.go create mode 100644 main_server.go diff --git a/main.go b/main.go index 02e68ef..5dbb7ca 100644 --- a/main.go +++ b/main.go @@ -1,80 +1,14 @@ package main import ( - "bytes" - "crypto/tls" - "crypto/x509" - "encoding/json" "flag" "fmt" - "io" "io/ioutil" "log" - "net" - "net/http" - "net/url" "os" - "path" - "path/filepath" - "regexp" "strconv" - "strings" - "sync" - "time" - - tunnel "git.sequentialread.com/forest/tunnel/tunnel-lib" ) -type ServerConfig struct { - DebugLog bool - ListenPort int // default 9056 - - // Domain is only used for validating the TLS client certificates - // when TLS is used. the cert's Subject CommonName is expected to be @ - // I did this because I believe this is a standard for TLS client certs, - // based on domain users/email addresses. - Domain string - - // MultiTenantMode ON: - // tenantId is required. ClientId must be formatted `.` - // clients will not be allowed to register listeners capturing all packets on a given port, - // they must specify a hostname, and they must prove that they own it (via a TXT record for example). - // Exception: Each client will get a few allocated ports for SSH & maybe etc??? - // - // MultiTenantMode OFF: - // tenantId is N/A. ClientId must be formatted `` - // clients can register listeners with any hostname including null, on any open port. - // - MultiTenantMode bool - MultiTenantInternalAPIListenPort int // default 9057 - MultiTenantInternalAPICaCertificateFile string - - CaCertificateFilesGlob string - ServerTlsKeyFile string - ServerTlsCertificateFile string - - Metrics MetricsConfig -} - -type ClientConfig struct { - DebugLog bool - ClientId string - ServerAddr string - Servers []string - ServiceToLocalAddrMap *map[string]string - CaCertificateFilesGlob string - ClientTlsKeyFile string - ClientTlsCertificateFile string - AdminUnixSocket string - Metrics MetricsConfig -} - -type ClientServer struct { - Client *tunnel.Client - ServerUrl *url.URL - ServerHostPort string -} - type MetricsConfig struct { PrometheusMetricsAPIPort int } @@ -88,57 +22,6 @@ type ListenerConfig struct { ClientId string } -type ClientState struct { - CurrentState string - LastState string -} - -type ManagementHttpHandler struct { - Domain string - MultiTenantMode bool - ControlHandler http.Handler -} - -type BandwidthCounter struct { - Inbound int64 - Outbound int64 -} - -type MultiTenantInternalAPI struct{} - -type PrometheusMetricsAPI struct { - MultiTenantServerMode bool - InboundByTenant map[string]int64 - OutboundByTenant map[string]int64 - InboundByService map[string]int64 - OutboundByService map[string]int64 -} - -type Tenant struct { - ReservedPorts []int - AuthorizedDomains []string -} - -type LiveConfigUpdate struct { - Listeners []ListenerConfig - ServiceToLocalAddrMap map[string]string -} - -type adminAPI struct{} - -// Server State -var listenersByTenant map[string][]ListenerConfig -var clientStatesMutex = &sync.Mutex{} -var tenantStatesMutex = &sync.Mutex{} -var clientStatesByTenant map[string]map[string]ClientState -var tenants map[string]Tenant -var server *tunnel.Server - -// Client State -var servers []ClientServer -var tlsClientConfig *tls.Config -var serviceToLocalAddrMap *map[string]string - func main() { mode := flag.String("mode", "", "Run client or server application. Allowed values: [client,server]") @@ -158,815 +41,6 @@ func main() { } -// client admin api handler for /liveconfig over unix socket -func (handler adminAPI) ServeHTTP(response http.ResponseWriter, request *http.Request) { - switch path.Clean(request.URL.Path) { - case "/liveconfig": - if request.Method == "PUT" { - requestBytes, err := ioutil.ReadAll(request.Body) - if err != nil { - log.Printf("adminAPI: request read error: %+v\n\n", err) - http.Error(response, "500 request read error", http.StatusInternalServerError) - return - } - var configUpdate LiveConfigUpdate - err = json.Unmarshal(requestBytes, &configUpdate) - if err != nil { - log.Printf("adminAPI: can't parse JSON: %+v\n\n", err) - http.Error(response, "400 bad request: can't parse JSON", http.StatusBadRequest) - return - } - - sendBytes, err := json.Marshal(configUpdate.Listeners) - if err != nil { - log.Printf("adminAPI: Listeners json serialization failed: %+v\n\n", err) - http.Error(response, "500 Listeners json serialization failed", http.StatusInternalServerError) - return - } - client := &http.Client{ - Transport: &http.Transport{ - TLSClientConfig: tlsClientConfig, - }, - Timeout: 10 * time.Second, - } - - // TODO make this concurrent requests, not one by one. - for _, server := range servers { - apiURL := fmt.Sprintf("https://%s/tunnels", server.ServerHostPort) - tunnelsRequest, err := http.NewRequest("PUT", apiURL, bytes.NewReader(sendBytes)) - if err != nil { - log.Printf("adminAPI: error creating tunnels request: %+v\n\n", err) - http.Error(response, "500 error creating tunnels request", http.StatusInternalServerError) - return - } - tunnelsRequest.Header.Add("content-type", "application/json") - - tunnelsResponse, err := client.Do(tunnelsRequest) - if err != nil { - log.Printf("adminAPI: Do(tunnelsRequest): %+v\n\n", err) - http.Error(response, "502 tunnels request failed", http.StatusBadGateway) - return - } - tunnelsResponseBytes, err := ioutil.ReadAll(tunnelsResponse.Body) - if err != nil { - log.Printf("adminAPI: tunnelsResponse read error: %+v\n\n", err) - http.Error(response, "502 tunnelsResponse read error", http.StatusBadGateway) - return - } - - if tunnelsResponse.StatusCode != http.StatusOK { - log.Printf( - "adminAPI: tunnelsRequest returned HTTP %d: %s\n\n", - tunnelsResponse.StatusCode, string(tunnelsResponseBytes), - ) - http.Error( - response, - fmt.Sprintf("502 tunnels request returned HTTP %d", tunnelsResponse.StatusCode), - http.StatusBadGateway, - ) - return - } - } - - serviceToLocalAddrMap = &configUpdate.ServiceToLocalAddrMap - - response.Header().Add("content-type", "application/json") - response.WriteHeader(http.StatusOK) - response.Write(requestBytes) - - } else { - response.Header().Set("Allow", "PUT") - http.Error(response, "405 method not allowed, try PUT", http.StatusMethodNotAllowed) - } - default: - http.Error(response, "404 not found, try PUT /liveconfig", http.StatusNotFound) - } - -} - -func runClient(configFileName *string) { - - configBytes := getConfigBytes(configFileName) - - var config ClientConfig - err := json.Unmarshal(configBytes, &config) - if err != nil { - log.Fatalf("runClient(): can't json.Unmarshal(configBytes, &config) because %s \n", err) - } - - servers := []ClientServer{} - makeServer := func(hostPort string) ClientServer { - serverURLString := fmt.Sprintf("https://%s", hostPort) - serverURL, err := url.Parse(serverURLString) - if err != nil { - log.Fatal(fmt.Errorf("failed to parse the ServerAddr (prefixed with https://) '%s' as a url", serverURLString)) - } - return ClientServer{ - ServerHostPort: hostPort, - ServerUrl: serverURL, - } - } - - if config.Servers != nil && len(config.Servers) > 0 { - if config.ServerAddr != "" { - log.Fatal("config contains both Servers and ServerAddr, only use one or the other") - } - for _, serverHostPort := range config.Servers { - servers = append(servers, makeServer(serverHostPort)) - } - } else { - servers = []ClientServer{makeServer(config.ServerAddr)} - } - - serviceToLocalAddrMap = config.ServiceToLocalAddrMap - - configToLog, _ := json.MarshalIndent(config, "", " ") - log.Printf("theshold client is starting up using config:\n%s\n", string(configToLog)) - - dialFunction := net.Dial - - cert, err := tls.LoadX509KeyPair(config.ClientTlsCertificateFile, config.ClientTlsKeyFile) - if err != nil { - log.Fatal(err) - } - - commonName := cert.Leaf.Subject.CommonName - clientIdDomain := strings.Split(commonName, "@") - - if len(clientIdDomain) != 2 { - log.Fatal(fmt.Errorf( - "expected TLS client certificate common name '%s' to match format '@'", commonName, - )) - } - - // This is enforced by the server anyways, so no need to enforce it here. - // This allows server URLs to use IP addresses, don't require DNS. - // if clientIdDomain[1] != serverURL.Hostname() { - // log.Fatal(fmt.Errorf( - // "expected TLS client certificate common name domain '%s' to match ServerAddr domain '%s'", - // clientIdDomain[1], serverURL.Hostname(), - // )) - // } - - if clientIdDomain[0] != config.ClientId { - log.Fatal(fmt.Errorf( - "expected TLS client certificate common name clientId '%s' to match ClientId '%s'", - clientIdDomain[0], config.ClientId, - )) - } - - certificates, err := filepath.Glob(config.CaCertificateFilesGlob) - if err != nil { - log.Fatal(err) - } - - caCertPool := x509.NewCertPool() - for _, filename := range certificates { - caCert, err := ioutil.ReadFile(filename) - if err != nil { - log.Fatal(err) - } - caCertPool.AppendCertsFromPEM(caCert) - } - - tlsClientConfig = &tls.Config{ - Certificates: []tls.Certificate{cert}, - RootCAs: caCertPool, - } - tlsClientConfig.BuildNameToCertificate() - - dialFunction = func(network, address string) (net.Conn, error) { - return tls.Dial(network, address, tlsClientConfig) - } - - go runClientAdminApi(config) - - fetchLocalAddr := func(service string) (string, error) { - //log.Printf("(*serviceToLocalAddrMap): %+v\n\n", (*serviceToLocalAddrMap)) - localAddr, hasLocalAddr := (*serviceToLocalAddrMap)[service] - if !hasLocalAddr { - return "", fmt.Errorf("service '%s' not configured. Set ServiceToLocalAddrMap in client config file or HTTP PUT /liveconfig over the AdminUnixSocket.", service) - } - return localAddr, nil - } - - for _, server := range servers { - clientStateChanges := make(chan *tunnel.ClientStateChange) - tunnelClientConfig := &tunnel.ClientConfig{ - DebugLog: config.DebugLog, - Identifier: config.ClientId, - ServerAddr: server.ServerHostPort, - FetchLocalAddr: fetchLocalAddr, - Dial: dialFunction, - StateChanges: clientStateChanges, - } - - client, err := tunnel.NewClient(tunnelClientConfig) - if err != nil { - log.Fatalf("runClient(): can't create tunnel client for %s because %v \n", server.ServerHostPort, err) - } - - go (func() { - for { - stateChange := <-clientStateChanges - log.Printf("%s clientStateChange: %s\n", server.ServerHostPort, stateChange.String()) - } - })() - - server.Client = client - go server.Client.Start() - } - - log.Print("runClient(): the client should be running now\n") -} - -func runClientAdminApi(config ClientConfig) { - - os.Remove(config.AdminUnixSocket) - - listenAddress, err := net.ResolveUnixAddr("unix", config.AdminUnixSocket) - if err != nil { - panic(fmt.Sprintf("runClient(): can't start because net.ResolveUnixAddr() returned %+v", err)) - } - - listener, err := net.ListenUnix("unix", listenAddress) - if err != nil { - panic(fmt.Sprintf("can't start because net.ListenUnix() returned %+v", err)) - } - log.Printf("AdminUnixSocket Listening: %v\n\n", config.AdminUnixSocket) - defer listener.Close() - - server := http.Server{ - Handler: adminAPI{}, - ReadTimeout: 10 * time.Second, - WriteTimeout: 10 * time.Second, - } - - err = server.Serve(listener) - if err != nil { - panic(fmt.Sprintf("AdminUnixSocket server returned %+v", err)) - } -} - -func validateCertificate(domain string, multiTenantMode bool, request *http.Request) (identifier string, tenantId string, err error) { - if len(request.TLS.PeerCertificates) != 1 { - return "", "", fmt.Errorf("expected exactly 1 TLS client certificate, got %d", len(request.TLS.PeerCertificates)) - } - certCommonName := request.TLS.PeerCertificates[0].Subject.CommonName - clientIdDomain := strings.Split(certCommonName, "@") - if len(clientIdDomain) != 2 { - return "", "", fmt.Errorf( - "expected TLS client certificate common name '%s' to match format '@'", certCommonName, - ) - } - if clientIdDomain[1] != domain { - return "", "", fmt.Errorf( - "expected TLS client certificate common name domain '%s' to match server domain '%s'", - clientIdDomain[1], domain, - ) - } - - identifier = clientIdDomain[0] - nodeId := identifier - - if multiTenantMode { - tenantIdNodeId := strings.Split(identifier, ".") - if len(tenantIdNodeId) != 2 { - return "", "", fmt.Errorf( - "expected TLS client certificate common name '%s' to match format '.@'", certCommonName, - ) - } - tenantId = tenantIdNodeId[0] - nodeId = tenantIdNodeId[1] - } - - mustMatchRegexp := regexp.MustCompile("(?i)^[a-z0-9]+([a-z0-9-_]*[a-z0-9]+)?$") - if !mustMatchRegexp.MatchString(nodeId) { - return "", "", fmt.Errorf("expected TLS client certificate common name nodeId '%s' to be a valid subdomain", nodeId) - } - - if tenantId != "" && !mustMatchRegexp.MatchString(tenantId) { - return "", "", fmt.Errorf("expected TLS client certificate common name tenantId '%s' to be a valid subdomain", tenantId) - } - - return identifier, tenantId, nil -} - -func runServer(configFileName *string) { - - configBytes := getConfigBytes(configFileName) - - var config ServerConfig - err := json.Unmarshal(configBytes, &config) - if err != nil { - fmt.Printf("runServer(): can't json.Unmarshal(configBytes, &config) because %s \n", err) - os.Exit(1) - } - - configToLog, _ := json.MarshalIndent(config, "", " ") - log.Printf("threshold server is starting up using config:\n%s\n", string(configToLog)) - - clientStateChangeChannel := make(chan *tunnel.ClientStateChange) - - var metricChannel chan tunnel.BandwidthMetric = nil - - // the Server should only collect metrics when in multi-tenant mode -- this is needed for billing - if config.MultiTenantMode { - metricChannel = make(chan tunnel.BandwidthMetric) - go exportMetrics(config.Metrics /*multiTenantServerMode: */, true, metricChannel) - } - - tunnelServerConfig := &tunnel.ServerConfig{ - StateChanges: clientStateChangeChannel, - ValidateCertificate: validateCertificate, - Bandwidth: metricChannel, - Domain: config.Domain, - DebugLog: config.DebugLog, - } - server, err = tunnel.NewServer(tunnelServerConfig) - if err != nil { - fmt.Printf("runServer(): can't create tunnel server because %s \n", err) - os.Exit(1) - } - - clientStatesByTenant = make(map[string]map[string]ClientState) - go (func() { - for { - clientStateChange := <-clientStateChangeChannel - previousState := "" - currentState := clientStateChange.Current.String() - tenantId := "" - if config.MultiTenantMode { - tenantIdNodeId := strings.Split(clientStateChange.Identifier, ".") - if len(tenantIdNodeId) != 2 { - fmt.Printf("runServer(): go func(): can't handle clientStateChange with malformed Identifier '%s' \n", clientStateChange.Identifier) - break - } - tenantId = tenantIdNodeId[0] - } - - clientStatesMutex.Lock() - if _, hasTenant := clientStatesByTenant[tenantId]; !hasTenant { - clientStatesByTenant[tenantId] = map[string]ClientState{} - } - fromMap, wasInMap := clientStatesByTenant[tenantId][clientStateChange.Identifier] - if wasInMap { - previousState = fromMap.CurrentState - } else { - previousState = clientStateChange.Previous.String() - } - if clientStateChange.Error != nil && clientStateChange.Error != io.EOF { - log.Printf("runServer(): recieved a client state change with an error: %s \n", clientStateChange.Error) - currentState = "ClientError" - } - clientStatesByTenant[tenantId][clientStateChange.Identifier] = ClientState{ - CurrentState: currentState, - LastState: previousState, - } - clientStatesMutex.Unlock() - } - })() - - certificates, err := filepath.Glob(config.CaCertificateFilesGlob) - if err != nil { - log.Fatal(err) - } - - caCertPool := x509.NewCertPool() - for _, filename := range certificates { - log.Printf("loading certificate %s, clients who have a key signed by this certificat will be allowed to connect", filename) - caCert, err := ioutil.ReadFile(filename) - if err != nil { - log.Fatal(err) - } - caCertPool.AppendCertsFromPEM(caCert) - } - - tlsConfig := &tls.Config{ - - ClientCAs: caCertPool, - ClientAuth: tls.RequireAndVerifyClientCert, - } - tlsConfig.BuildNameToCertificate() - - httpsManagementServer := &http.Server{ - Addr: fmt.Sprintf(":%d", config.ListenPort), - TLSConfig: tlsConfig, - Handler: &(ManagementHttpHandler{ - Domain: config.Domain, - MultiTenantMode: config.MultiTenantMode, - ControlHandler: server, - }), - } - - if config.MultiTenantMode { - go (func() { - caCertPool := x509.NewCertPool() - caCert, err := ioutil.ReadFile(config.MultiTenantInternalAPICaCertificateFile) - if err != nil { - log.Fatal(err) - } - caCertPool.AppendCertsFromPEM(caCert) - tlsConfig := &tls.Config{ - ClientCAs: caCertPool, - ClientAuth: tls.RequireAndVerifyClientCert, - } - tlsConfig.BuildNameToCertificate() - - multiTenantInternalServer := &http.Server{ - Addr: fmt.Sprintf(":%d", config.MultiTenantInternalAPIListenPort), - TLSConfig: tlsConfig, - Handler: &MultiTenantInternalAPI{}, - } - - err = multiTenantInternalServer.ListenAndServeTLS(config.ServerTlsCertificateFile, config.ServerTlsKeyFile) - panic(err) - })() - } - - log.Print("runServer(): the server should be running now\n") - err = httpsManagementServer.ListenAndServeTLS(config.ServerTlsCertificateFile, config.ServerTlsKeyFile) - panic(err) - -} - -func setListeners(tenantId string, listenerConfigs []ListenerConfig) (int, string) { - currentListenersThatCanKeepRunning := make([]ListenerConfig, 0) - newListenersThatHaveToBeAdded := make([]ListenerConfig, 0) - - for _, newListenerConfig := range listenerConfigs { - clientState, everHeardOfClientBefore := clientStatesByTenant[tenantId][newListenerConfig.ClientId] - if !everHeardOfClientBefore { - return http.StatusNotFound, fmt.Sprintf("Client %s Not Found", newListenerConfig.ClientId) - } - if clientState.CurrentState != tunnel.ClientConnected.String() { - return http.StatusNotFound, fmt.Sprintf("Client %s is not connected it is %s", newListenerConfig.ClientId, clientState.CurrentState) - } - } - - for _, existingListener := range listenersByTenant[tenantId] { - canKeepRunning := false - for _, newListenerConfig := range listenerConfigs { - if compareListenerConfigs(existingListener, newListenerConfig) { - canKeepRunning = true - } - } - - if !canKeepRunning { - listenAddress := net.ParseIP(existingListener.ListenAddress) - if listenAddress == nil { - return http.StatusBadRequest, fmt.Sprintf("Bad Request: \"%s\" is not an IP address.", existingListener.ListenAddress) - } - - server.DeleteAddr(listenAddress, existingListener.ListenPort, existingListener.ListenHostnameGlob) - - } else { - currentListenersThatCanKeepRunning = append(currentListenersThatCanKeepRunning, existingListener) - } - } - - for _, newListenerConfig := range listenerConfigs { - hasToBeAdded := true - for _, existingListener := range listenersByTenant[tenantId] { - if compareListenerConfigs(existingListener, newListenerConfig) { - hasToBeAdded = false - } - } - - if hasToBeAdded { - listenAddress := net.ParseIP(newListenerConfig.ListenAddress) - //fmt.Printf("str: %s, listenAddress: %s\n\n", newListenerConfig.ListenAddress, listenAddress) - if listenAddress == nil { - return http.StatusBadRequest, fmt.Sprintf("Bad Request: \"%s\" is not an IP address.", newListenerConfig.ListenAddress) - } - err := server.AddAddr( - listenAddress, - newListenerConfig.ListenPort, - newListenerConfig.ListenHostnameGlob, - newListenerConfig.ClientId, - newListenerConfig.HaProxyProxyProtocol, - newListenerConfig.BackEndService, - ) - - if err != nil { - if strings.Contains(err.Error(), "already in use") { - return http.StatusConflict, fmt.Sprintf("Port Conflict: Port %s is reserved or already in use", listenAddress) - } - - log.Printf("setListeners(): can't net.Listen(\"tcp\", \"%s\") because %s \n", listenAddress, err) - return http.StatusInternalServerError, "Unknown Listening Error" - } - - newListenersThatHaveToBeAdded = append(newListenersThatHaveToBeAdded, newListenerConfig) - } - } - - listenersByTenant[tenantId] = append(currentListenersThatCanKeepRunning, newListenersThatHaveToBeAdded...) - - return http.StatusOK, "ok" - -} - -func exportMetrics(config MetricsConfig, multiTenantServerMode bool, bandwidth <-chan tunnel.BandwidthMetric) { - metricsAPI := &PrometheusMetricsAPI{ - MultiTenantServerMode: multiTenantServerMode, - InboundByTenant: map[string]int64{}, - OutboundByTenant: map[string]int64{}, - InboundByService: map[string]int64{}, - OutboundByService: map[string]int64{}, - } - - go (func() { - for { - metric := <-bandwidth - if multiTenantServerMode { - tenantIdNodeId := strings.Split(metric.ClientId, ".") - if len(tenantIdNodeId) != 2 { - panic(fmt.Errorf("malformed metric.ClientId '%s', expected .", metric.ClientId)) - } - if metric.Inbound { - metricsAPI.InboundByTenant[tenantIdNodeId[0]] += int64(metric.Bytes) - } else { - metricsAPI.OutboundByTenant[tenantIdNodeId[0]] += int64(metric.Bytes) - } - } else { - if metric.Inbound { - metricsAPI.InboundByService[metric.Service] += int64(metric.Bytes) - } else { - metricsAPI.OutboundByService[metric.Service] += int64(metric.Bytes) - } - } - } - })() - - go (func() { - metricsServer := &http.Server{ - Addr: fmt.Sprintf(":%d", config.PrometheusMetricsAPIPort), - Handler: metricsAPI, - } - err := metricsServer.ListenAndServe() - panic(err) - })() -} - -func (s *PrometheusMetricsAPI) ServeHTTP(responseWriter http.ResponseWriter, request *http.Request) { - - getMillisecondsSinceUnixEpoch := func() int64 { - return time.Now().UnixNano() / int64(time.Millisecond) - } - - writeMetric := func(inbound map[string]int64, outbound map[string]int64, name, tag, desc string) { - timestamp := getMillisecondsSinceUnixEpoch() - responseWriter.Write([]byte(fmt.Sprintf("# HELP %s %s\n", name, desc))) - responseWriter.Write([]byte(fmt.Sprintf("# TYPE %s counter\n", name))) - for id, bytez := range inbound { - responseWriter.Write([]byte(fmt.Sprintf("%s{%s=\"%s\",direction=\"inbound\"} %d %d\n", name, tag, id, bytez, timestamp))) - } - for id, bytez := range outbound { - responseWriter.Write([]byte(fmt.Sprintf("%s{%s=\"%s\",direction=\"outbound\"} %d %d\n", name, tag, id, bytez, timestamp))) - } - } - - if strings.Contains(request.Header.Get("Accept"), "application/json") { - var bytez []byte - var err error - if s.MultiTenantServerMode { - bytez, err = json.MarshalIndent(PrometheusMetricsAPI{ - InboundByTenant: s.InboundByTenant, - OutboundByTenant: s.OutboundByTenant, - }, "", " ") - } else { - bytez, err = json.MarshalIndent(PrometheusMetricsAPI{ - InboundByService: s.InboundByService, - OutboundByService: s.OutboundByService, - }, "", " ") - } - - if err != nil { - log.Printf(fmt.Sprintf("500 internal server error: %s", err)) - http.Error(responseWriter, "500 internal server error", http.StatusInternalServerError) - return - } - - responseWriter.Header().Set("Content-Type", "application/json") - responseWriter.Write(bytez) - } else { - responseWriter.Header().Set("Content-Type", "text/plain; version=0.0.4") - - if s.MultiTenantServerMode { - writeMetric(s.InboundByTenant, s.OutboundByTenant, "bandwidth_by_tenant", "tenant", "bandwidth usage by tenant in bytes, excluding usage from control protocol.") - } else { - writeMetric(s.InboundByService, s.OutboundByService, "bandwidth_by_service", "service", "bandwidth usage by service in bytes.") - } - } -} - -func compareListenerConfigs(a, b ListenerConfig) bool { - return (a.ListenPort == b.ListenPort && - a.ListenAddress == b.ListenAddress && - a.ListenHostnameGlob == b.ListenHostnameGlob && - a.BackEndService == b.BackEndService && - a.ClientId == b.ClientId && - a.HaProxyProxyProtocol == b.HaProxyProxyProtocol) -} - -func (s *MultiTenantInternalAPI) ServeHTTP(responseWriter http.ResponseWriter, request *http.Request) { - switch path.Clean(request.URL.Path) { - case "/tenants": - if request.Method == "GET" || request.Method == "PUT" { - if request.Method == "PUT" { - if request.Header.Get("Content-Type") != "application/json" { - http.Error(responseWriter, "415 Unsupported Media Type: Content-Type must be application/json", http.StatusUnsupportedMediaType) - } else { - bodyBytes, err := ioutil.ReadAll(request.Body) - if err != nil { - http.Error(responseWriter, "500 Read Error", http.StatusInternalServerError) - return - } - var newTenants map[string]Tenant - err = json.Unmarshal(bodyBytes, &newTenants) - if err != nil { - http.Error(responseWriter, "422 Unprocessable Entity: Can't Parse JSON", http.StatusUnprocessableEntity) - return - } - tenantStatesMutex.Lock() - tenants = newTenants - tenantStatesMutex.Unlock() - } - } - - tenantStatesMutex.Lock() - bytes, err := json.Marshal(tenants) - tenantStatesMutex.Unlock() - if err != nil { - http.Error(responseWriter, "500 JSON Marshal Error", http.StatusInternalServerError) - return - } - responseWriter.Header().Set("Content-Type", "application/json") - responseWriter.Write(bytes) - - } else { - responseWriter.Header().Set("Allow", "GET, PUT") - http.Error(responseWriter, "405 Method Not Allowed, try GET or PUT", http.StatusMethodNotAllowed) - } - case "/ping": - if request.Method == "GET" { - fmt.Fprint(responseWriter, "pong") - } else { - responseWriter.Header().Set("Allow", "GET") - http.Error(responseWriter, "405 method not allowed, try GET", http.StatusMethodNotAllowed) - } - default: - http.Error(responseWriter, "404 Not Found, try /tenants or /ping", http.StatusNotFound) - } -} - -func (s *ManagementHttpHandler) ServeHTTP(responseWriter http.ResponseWriter, request *http.Request) { - - _, tenantId, err := validateCertificate(s.Domain, s.MultiTenantMode, request) - if err != nil { - http.Error(responseWriter, fmt.Sprintf("400 bad request: %s", err.Error()), http.StatusBadRequest) - return - } - if _, hasTenant := clientStatesByTenant[tenantId]; !hasTenant { - clientStatesByTenant[tenantId] = map[string]ClientState{} - } - if _, hasTenant := listenersByTenant[tenantId]; !hasTenant { - listenersByTenant[tenantId] = []ListenerConfig{} - } - - switch path.Clean(request.URL.Path) { - case "/clients": - if request.Method == "GET" { - clientStatesMutex.Lock() - - bytes, err := json.Marshal(clientStatesByTenant[tenantId]) - clientStatesMutex.Unlock() - if err != nil { - http.Error(responseWriter, "500 JSON Marshal Error", http.StatusInternalServerError) - return - } - responseWriter.Header().Set("Content-Type", "application/json") - responseWriter.Write(bytes) - - } else { - responseWriter.Header().Set("Allow", "GET") - http.Error(responseWriter, "405 Method Not Allowed, try GET", http.StatusMethodNotAllowed) - } - case "/tunnels": - if request.Method == "PUT" { - if request.Header.Get("Content-Type") != "application/json" { - http.Error(responseWriter, "415 Unsupported Media Type: Content-Type must be application/json", http.StatusUnsupportedMediaType) - } else { - bodyBytes, err := ioutil.ReadAll(request.Body) - if err != nil { - http.Error(responseWriter, "500 Read Error", http.StatusInternalServerError) - return - } - var listenerConfigs []ListenerConfig - err = json.Unmarshal(bodyBytes, &listenerConfigs) - if err != nil { - http.Error(responseWriter, "422 Unprocessable Entity: Can't Parse JSON", http.StatusUnprocessableEntity) - return - } - - if s.MultiTenantMode { - for _, listenerConfig := range listenerConfigs { - tenantIdNodeId := strings.Split(listenerConfig.ClientId, ".") - if len(tenantIdNodeId) != 2 { - http.Error( - responseWriter, - fmt.Sprintf( - "400 Bad Request: invalid ClientId '%s'. It needs to be in the form '.'", - listenerConfig.ClientId, - ), - http.StatusBadRequest, - ) - return - } - tenant, hasTenant := tenants[tenantIdNodeId[0]] - if !hasTenant { - http.Error( - responseWriter, - fmt.Sprintf("400 Bad Request: unknown tenantId '%s'", tenantIdNodeId[0]), - http.StatusBadRequest, - ) - } - isAuthorizedDomain := false - for _, tenantAuthorizedDomain := range tenant.AuthorizedDomains { - isSubdomain := strings.HasSuffix(listenerConfig.ListenHostnameGlob, fmt.Sprintf(".%s", tenantAuthorizedDomain)) - if (tenantAuthorizedDomain == listenerConfig.ListenHostnameGlob) || isSubdomain { - isAuthorizedDomain = true - break - } - } - if listenerConfig.ListenHostnameGlob != "" && !isAuthorizedDomain { - http.Error( - responseWriter, - fmt.Sprintf( - "400 Bad Request: ListenHostnameGlob '%s' is not covered by any of your authorized domains [%s]", - listenerConfig.ListenHostnameGlob, - strings.Join(stringSliceMap(tenant.AuthorizedDomains, func(x string) string { return fmt.Sprintf("'%s'", x) }), ", "), - ), - http.StatusBadRequest, - ) - } - - if listenerConfig.ListenHostnameGlob == "" { - isReservedPort := false - for _, tenantReservedPort := range tenant.ReservedPorts { - if listenerConfig.ListenPort == tenantReservedPort { - isReservedPort = true - break - } - } - if !isReservedPort { - http.Error( - responseWriter, - fmt.Sprintf( - "400 Bad Request: ListenHostnameGlob is empty and ListenPort '%d' is not one of your reserved ports [%s]", - listenerConfig.ListenPort, - strings.Join(intSlice2StringSlice(tenant.ReservedPorts), ", "), - ), - http.StatusBadRequest, - ) - } - } - } - } - - statusCode, errorMessage := setListeners(tenantId, listenerConfigs) - - if statusCode != 200 { - http.Error(responseWriter, errorMessage, statusCode) - return - } - - bytes, err := json.Marshal(listenerConfigs) - if err != nil { - http.Error(responseWriter, "500 JSON Marshal Error", http.StatusInternalServerError) - return - } - - responseWriter.Header().Set("Content-Type", "application/json") - responseWriter.Write(bytes) - } - } else { - responseWriter.Header().Set("Allow", "PUT") - http.Error(responseWriter, "405 Method Not Allowed, try PUT", http.StatusMethodNotAllowed) - } - case "/ping": - if request.Method == "GET" { - fmt.Fprint(responseWriter, "pong") - } else { - responseWriter.Header().Set("Allow", "GET") - http.Error(responseWriter, "405 method not allowed, try GET", http.StatusMethodNotAllowed) - } - default: - s.ControlHandler.ServeHTTP(responseWriter, request) - } -} - func getConfigBytes(configFileName *string) []byte { if configFileName != nil { configBytes, err := ioutil.ReadFile(*configFileName) diff --git a/main_client.go b/main_client.go new file mode 100644 index 0000000..8c8fc3a --- /dev/null +++ b/main_client.go @@ -0,0 +1,312 @@ +package main + +import ( + "bytes" + "crypto/tls" + "crypto/x509" + "encoding/json" + "fmt" + "io/ioutil" + "log" + "net" + "net/http" + "net/url" + "os" + "path" + "path/filepath" + "strings" + "time" + + tunnel "git.sequentialread.com/forest/tunnel/tunnel-lib" +) + +type ClientConfig struct { + DebugLog bool + ClientId string + MultiTenantSchedulerServer string + ServerAddr string + Servers []string + ServiceToLocalAddrMap *map[string]string + CaCertificateFilesGlob string + ClientTlsKeyFile string + ClientTlsCertificateFile string + AdminUnixSocket string + Metrics MetricsConfig +} + +type ClientServer struct { + Client *tunnel.Client + ServerUrl *url.URL + ServerHostPort string +} + +type LiveConfigUpdate struct { + Listeners []ListenerConfig + ServiceToLocalAddrMap map[string]string +} + +type clientAdminAPI struct{} + +// Client State +var clientServers []ClientServer +var tlsClientConfig *tls.Config +var serviceToLocalAddrMap *map[string]string + +func runClient(configFileName *string) { + + configBytes := getConfigBytes(configFileName) + + var config ClientConfig + err := json.Unmarshal(configBytes, &config) + if err != nil { + log.Fatalf("runClient(): can't json.Unmarshal(configBytes, &config) because %s \n", err) + } + + clientServers = []ClientServer{} + makeServer := func(hostPort string) ClientServer { + serverURLString := fmt.Sprintf("https://%s", hostPort) + serverURL, err := url.Parse(serverURLString) + if err != nil { + log.Fatal(fmt.Errorf("failed to parse the ServerAddr (prefixed with https://) '%s' as a url", serverURLString)) + } + return ClientServer{ + ServerHostPort: hostPort, + ServerUrl: serverURL, + } + } + + if config.MultiTenantSchedulerServer != "" { + if config.ServerAddr != "" { + log.Fatal("config contains both MultiTenantSchedulerServer and ServerAddr, only use one or the other") + } + if config.Servers != nil && len(config.Servers) > 0 { + log.Fatal("config contains both MultiTenantSchedulerServer and Servers, only use one or the other") + } + // TODO Grab server host/ports from greenhouse + + } else if config.Servers != nil && len(config.Servers) > 0 { + if config.ServerAddr != "" { + log.Fatal("config contains both Servers and ServerAddr, only use one or the other") + } + for _, serverHostPort := range config.Servers { + clientServers = append(clientServers, makeServer(serverHostPort)) + } + } else { + clientServers = []ClientServer{makeServer(config.ServerAddr)} + } + + serviceToLocalAddrMap = config.ServiceToLocalAddrMap + + configToLog, _ := json.MarshalIndent(config, "", " ") + log.Printf("theshold client is starting up using config:\n%s\n", string(configToLog)) + + dialFunction := net.Dial + + cert, err := tls.LoadX509KeyPair(config.ClientTlsCertificateFile, config.ClientTlsKeyFile) + if err != nil { + log.Fatal(err) + } + + commonName := cert.Leaf.Subject.CommonName + clientIdDomain := strings.Split(commonName, "@") + + if len(clientIdDomain) != 2 { + log.Fatal(fmt.Errorf( + "expected TLS client certificate common name '%s' to match format '@'", commonName, + )) + } + + // This is enforced by the server anyways, so no need to enforce it here. + // This allows server URLs to use IP addresses, don't require DNS. + // if clientIdDomain[1] != serverURL.Hostname() { + // log.Fatal(fmt.Errorf( + // "expected TLS client certificate common name domain '%s' to match ServerAddr domain '%s'", + // clientIdDomain[1], serverURL.Hostname(), + // )) + // } + + if clientIdDomain[0] != config.ClientId { + log.Fatal(fmt.Errorf( + "expected TLS client certificate common name clientId '%s' to match ClientId '%s'", + clientIdDomain[0], config.ClientId, + )) + } + + certificates, err := filepath.Glob(config.CaCertificateFilesGlob) + if err != nil { + log.Fatal(err) + } + + caCertPool := x509.NewCertPool() + for _, filename := range certificates { + caCert, err := ioutil.ReadFile(filename) + if err != nil { + log.Fatal(err) + } + caCertPool.AppendCertsFromPEM(caCert) + } + + tlsClientConfig = &tls.Config{ + Certificates: []tls.Certificate{cert}, + RootCAs: caCertPool, + } + tlsClientConfig.BuildNameToCertificate() + + dialFunction = func(network, address string) (net.Conn, error) { + return tls.Dial(network, address, tlsClientConfig) + } + + go runClientAdminApi(config) + + fetchLocalAddr := func(service string) (string, error) { + //log.Printf("(*serviceToLocalAddrMap): %+v\n\n", (*serviceToLocalAddrMap)) + localAddr, hasLocalAddr := (*serviceToLocalAddrMap)[service] + if !hasLocalAddr { + return "", fmt.Errorf("service '%s' not configured. Set ServiceToLocalAddrMap in client config file or HTTP PUT /liveconfig over the AdminUnixSocket.", service) + } + return localAddr, nil + } + + for _, server := range clientServers { + clientStateChanges := make(chan *tunnel.ClientStateChange) + tunnelClientConfig := &tunnel.ClientConfig{ + DebugLog: config.DebugLog, + Identifier: config.ClientId, + ServerAddr: server.ServerHostPort, + FetchLocalAddr: fetchLocalAddr, + Dial: dialFunction, + StateChanges: clientStateChanges, + } + + client, err := tunnel.NewClient(tunnelClientConfig) + if err != nil { + log.Fatalf("runClient(): can't create tunnel client for %s because %v \n", server.ServerHostPort, err) + } + + go (func() { + for { + stateChange := <-clientStateChanges + log.Printf("%s clientStateChange: %s\n", server.ServerHostPort, stateChange.String()) + } + })() + + server.Client = client + go server.Client.Start() + } + + log.Print("runClient(): the client should be running now\n") +} + +func runClientAdminApi(config ClientConfig) { + + os.Remove(config.AdminUnixSocket) + + listenAddress, err := net.ResolveUnixAddr("unix", config.AdminUnixSocket) + if err != nil { + panic(fmt.Sprintf("runClient(): can't start because net.ResolveUnixAddr() returned %+v", err)) + } + + listener, err := net.ListenUnix("unix", listenAddress) + if err != nil { + panic(fmt.Sprintf("can't start because net.ListenUnix() returned %+v", err)) + } + log.Printf("AdminUnixSocket Listening: %v\n\n", config.AdminUnixSocket) + defer listener.Close() + + server := http.Server{ + Handler: clientAdminAPI{}, + ReadTimeout: 10 * time.Second, + WriteTimeout: 10 * time.Second, + } + + err = server.Serve(listener) + if err != nil { + panic(fmt.Sprintf("AdminUnixSocket server returned %+v", err)) + } +} + +// client admin api handler for /liveconfig over unix socket +func (handler clientAdminAPI) ServeHTTP(response http.ResponseWriter, request *http.Request) { + switch path.Clean(request.URL.Path) { + case "/liveconfig": + if request.Method == "PUT" { + requestBytes, err := ioutil.ReadAll(request.Body) + if err != nil { + log.Printf("clientAdminAPI: request read error: %+v\n\n", err) + http.Error(response, "500 request read error", http.StatusInternalServerError) + return + } + var configUpdate LiveConfigUpdate + err = json.Unmarshal(requestBytes, &configUpdate) + if err != nil { + log.Printf("clientAdminAPI: can't parse JSON: %+v\n\n", err) + http.Error(response, "400 bad request: can't parse JSON", http.StatusBadRequest) + return + } + + sendBytes, err := json.Marshal(configUpdate.Listeners) + if err != nil { + log.Printf("clientAdminAPI: Listeners json serialization failed: %+v\n\n", err) + http.Error(response, "500 Listeners json serialization failed", http.StatusInternalServerError) + return + } + client := &http.Client{ + Transport: &http.Transport{ + TLSClientConfig: tlsClientConfig, + }, + Timeout: 10 * time.Second, + } + + // TODO make this concurrent requests, not one by one. + for _, server := range clientServers { + apiURL := fmt.Sprintf("https://%s/tunnels", server.ServerHostPort) + tunnelsRequest, err := http.NewRequest("PUT", apiURL, bytes.NewReader(sendBytes)) + if err != nil { + log.Printf("clientAdminAPI: error creating tunnels request: %+v\n\n", err) + http.Error(response, "500 error creating tunnels request", http.StatusInternalServerError) + return + } + tunnelsRequest.Header.Add("content-type", "application/json") + + tunnelsResponse, err := client.Do(tunnelsRequest) + if err != nil { + log.Printf("clientAdminAPI: Do(tunnelsRequest): %+v\n\n", err) + http.Error(response, "502 tunnels request failed", http.StatusBadGateway) + return + } + tunnelsResponseBytes, err := ioutil.ReadAll(tunnelsResponse.Body) + if err != nil { + log.Printf("clientAdminAPI: tunnelsResponse read error: %+v\n\n", err) + http.Error(response, "502 tunnelsResponse read error", http.StatusBadGateway) + return + } + + if tunnelsResponse.StatusCode != http.StatusOK { + log.Printf( + "clientAdminAPI: tunnelsRequest returned HTTP %d: %s\n\n", + tunnelsResponse.StatusCode, string(tunnelsResponseBytes), + ) + http.Error( + response, + fmt.Sprintf("502 tunnels request returned HTTP %d", tunnelsResponse.StatusCode), + http.StatusBadGateway, + ) + return + } + } + + serviceToLocalAddrMap = &configUpdate.ServiceToLocalAddrMap + + response.Header().Add("content-type", "application/json") + response.WriteHeader(http.StatusOK) + response.Write(requestBytes) + + } else { + response.Header().Set("Allow", "PUT") + http.Error(response, "405 method not allowed, try PUT", http.StatusMethodNotAllowed) + } + default: + http.Error(response, "404 not found, try PUT /liveconfig", http.StatusNotFound) + } + +} diff --git a/main_server.go b/main_server.go new file mode 100644 index 0000000..7bb8adf --- /dev/null +++ b/main_server.go @@ -0,0 +1,651 @@ +package main + +import ( + "crypto/tls" + "crypto/x509" + "encoding/json" + "fmt" + "io" + "io/ioutil" + "log" + "net" + "net/http" + "os" + "path" + "path/filepath" + "regexp" + "strings" + "sync" + "time" + + tunnel "git.sequentialread.com/forest/tunnel/tunnel-lib" +) + +type ServerConfig struct { + DebugLog bool + ListenPort int // default 9056 + + // Domain is only used for validating the TLS client certificates + // when TLS is used. the cert's Subject CommonName is expected to be @ + // I did this because I believe this is a standard for TLS client certs, + // based on domain users/email addresses. + Domain string + + // MultiTenantMode ON: + // tenantId is required. ClientId must be formatted `.` + // clients will not be allowed to register listeners capturing all packets on a given port, + // they must specify a hostname, and they must prove that they own it (via a TXT record for example). + // Exception: Each client will get a few allocated ports for SSH & maybe etc??? + // + // MultiTenantMode OFF: + // tenantId is N/A. ClientId must be formatted `` + // clients can register listeners with any hostname including null, on any open port. + // + MultiTenantMode bool + MultiTenantInternalAPIListenPort int // default 9057 + MultiTenantInternalAPICaCertificateFile string + + CaCertificateFilesGlob string + ServerTlsKeyFile string + ServerTlsCertificateFile string + + Metrics MetricsConfig +} + +type ClientState struct { + CurrentState string + LastState string +} + +type ManagementHttpHandler struct { + Domain string + MultiTenantMode bool + ControlHandler http.Handler +} + +type BandwidthCounter struct { + Inbound int64 + Outbound int64 +} + +type MultiTenantInternalAPI struct{} + +type PrometheusMetricsAPI struct { + MultiTenantServerMode bool + InboundByTenant map[string]int64 + OutboundByTenant map[string]int64 + InboundByService map[string]int64 + OutboundByService map[string]int64 +} + +type Tenant struct { + ReservedPorts []int + AuthorizedDomains []string +} + +// Server State +var listenersByTenant map[string][]ListenerConfig +var clientStatesMutex = &sync.Mutex{} +var tenantStatesMutex = &sync.Mutex{} +var clientStatesByTenant map[string]map[string]ClientState +var tenants map[string]Tenant +var server *tunnel.Server + +func runServer(configFileName *string) { + + configBytes := getConfigBytes(configFileName) + + var config ServerConfig + err := json.Unmarshal(configBytes, &config) + if err != nil { + fmt.Printf("runServer(): can't json.Unmarshal(configBytes, &config) because %s \n", err) + os.Exit(1) + } + + configToLog, _ := json.MarshalIndent(config, "", " ") + log.Printf("threshold server is starting up using config:\n%s\n", string(configToLog)) + + clientStateChangeChannel := make(chan *tunnel.ClientStateChange) + + var metricChannel chan tunnel.BandwidthMetric = nil + + // the Server should only collect metrics when in multi-tenant mode -- this is needed for billing + if config.MultiTenantMode { + metricChannel = make(chan tunnel.BandwidthMetric) + go exportMetrics(config.Metrics /*multiTenantServerMode: */, true, metricChannel) + } + + tunnelServerConfig := &tunnel.ServerConfig{ + StateChanges: clientStateChangeChannel, + ValidateCertificate: validateCertificate, + Bandwidth: metricChannel, + Domain: config.Domain, + DebugLog: config.DebugLog, + } + server, err = tunnel.NewServer(tunnelServerConfig) + if err != nil { + fmt.Printf("runServer(): can't create tunnel server because %s \n", err) + os.Exit(1) + } + + clientStatesByTenant = make(map[string]map[string]ClientState) + go (func() { + for { + clientStateChange := <-clientStateChangeChannel + previousState := "" + currentState := clientStateChange.Current.String() + tenantId := "" + if config.MultiTenantMode { + tenantIdNodeId := strings.Split(clientStateChange.Identifier, ".") + if len(tenantIdNodeId) != 2 { + fmt.Printf("runServer(): go func(): can't handle clientStateChange with malformed Identifier '%s' \n", clientStateChange.Identifier) + break + } + tenantId = tenantIdNodeId[0] + } + + clientStatesMutex.Lock() + if _, hasTenant := clientStatesByTenant[tenantId]; !hasTenant { + clientStatesByTenant[tenantId] = map[string]ClientState{} + } + fromMap, wasInMap := clientStatesByTenant[tenantId][clientStateChange.Identifier] + if wasInMap { + previousState = fromMap.CurrentState + } else { + previousState = clientStateChange.Previous.String() + } + if clientStateChange.Error != nil && clientStateChange.Error != io.EOF { + log.Printf("runServer(): recieved a client state change with an error: %s \n", clientStateChange.Error) + currentState = "ClientError" + } + clientStatesByTenant[tenantId][clientStateChange.Identifier] = ClientState{ + CurrentState: currentState, + LastState: previousState, + } + clientStatesMutex.Unlock() + } + })() + + certificates, err := filepath.Glob(config.CaCertificateFilesGlob) + if err != nil { + log.Fatal(err) + } + + caCertPool := x509.NewCertPool() + for _, filename := range certificates { + log.Printf("loading certificate %s, clients who have a key signed by this certificat will be allowed to connect", filename) + caCert, err := ioutil.ReadFile(filename) + if err != nil { + log.Fatal(err) + } + caCertPool.AppendCertsFromPEM(caCert) + } + + tlsConfig := &tls.Config{ + + ClientCAs: caCertPool, + ClientAuth: tls.RequireAndVerifyClientCert, + } + tlsConfig.BuildNameToCertificate() + + httpsManagementServer := &http.Server{ + Addr: fmt.Sprintf(":%d", config.ListenPort), + TLSConfig: tlsConfig, + Handler: &(ManagementHttpHandler{ + Domain: config.Domain, + MultiTenantMode: config.MultiTenantMode, + ControlHandler: server, + }), + } + + if config.MultiTenantMode { + go (func() { + caCertPool := x509.NewCertPool() + caCert, err := ioutil.ReadFile(config.MultiTenantInternalAPICaCertificateFile) + if err != nil { + log.Fatal(err) + } + caCertPool.AppendCertsFromPEM(caCert) + tlsConfig := &tls.Config{ + ClientCAs: caCertPool, + ClientAuth: tls.RequireAndVerifyClientCert, + } + tlsConfig.BuildNameToCertificate() + + multiTenantInternalServer := &http.Server{ + Addr: fmt.Sprintf(":%d", config.MultiTenantInternalAPIListenPort), + TLSConfig: tlsConfig, + Handler: &MultiTenantInternalAPI{}, + } + + err = multiTenantInternalServer.ListenAndServeTLS(config.ServerTlsCertificateFile, config.ServerTlsKeyFile) + panic(err) + })() + } + + log.Print("runServer(): the server should be running now\n") + err = httpsManagementServer.ListenAndServeTLS(config.ServerTlsCertificateFile, config.ServerTlsKeyFile) + panic(err) + +} + +func validateCertificate(domain string, multiTenantMode bool, request *http.Request) (identifier string, tenantId string, err error) { + if len(request.TLS.PeerCertificates) != 1 { + return "", "", fmt.Errorf("expected exactly 1 TLS client certificate, got %d", len(request.TLS.PeerCertificates)) + } + certCommonName := request.TLS.PeerCertificates[0].Subject.CommonName + clientIdDomain := strings.Split(certCommonName, "@") + if len(clientIdDomain) != 2 { + return "", "", fmt.Errorf( + "expected TLS client certificate common name '%s' to match format '@'", certCommonName, + ) + } + if clientIdDomain[1] != domain { + return "", "", fmt.Errorf( + "expected TLS client certificate common name domain '%s' to match server domain '%s'", + clientIdDomain[1], domain, + ) + } + + identifier = clientIdDomain[0] + nodeId := identifier + + if multiTenantMode { + tenantIdNodeId := strings.Split(identifier, ".") + if len(tenantIdNodeId) != 2 { + return "", "", fmt.Errorf( + "expected TLS client certificate common name '%s' to match format '.@'", certCommonName, + ) + } + tenantId = tenantIdNodeId[0] + nodeId = tenantIdNodeId[1] + } + + mustMatchRegexp := regexp.MustCompile("(?i)^[a-z0-9]+([a-z0-9-_]*[a-z0-9]+)?$") + if !mustMatchRegexp.MatchString(nodeId) { + return "", "", fmt.Errorf("expected TLS client certificate common name nodeId '%s' to be a valid subdomain", nodeId) + } + + if tenantId != "" && !mustMatchRegexp.MatchString(tenantId) { + return "", "", fmt.Errorf("expected TLS client certificate common name tenantId '%s' to be a valid subdomain", tenantId) + } + + return identifier, tenantId, nil +} + +func setListeners(tenantId string, listenerConfigs []ListenerConfig) (int, string) { + currentListenersThatCanKeepRunning := make([]ListenerConfig, 0) + newListenersThatHaveToBeAdded := make([]ListenerConfig, 0) + + for _, newListenerConfig := range listenerConfigs { + clientState, everHeardOfClientBefore := clientStatesByTenant[tenantId][newListenerConfig.ClientId] + if !everHeardOfClientBefore { + return http.StatusNotFound, fmt.Sprintf("Client %s Not Found", newListenerConfig.ClientId) + } + if clientState.CurrentState != tunnel.ClientConnected.String() { + return http.StatusNotFound, fmt.Sprintf("Client %s is not connected it is %s", newListenerConfig.ClientId, clientState.CurrentState) + } + } + + for _, existingListener := range listenersByTenant[tenantId] { + canKeepRunning := false + for _, newListenerConfig := range listenerConfigs { + if compareListenerConfigs(existingListener, newListenerConfig) { + canKeepRunning = true + } + } + + if !canKeepRunning { + listenAddress := net.ParseIP(existingListener.ListenAddress) + if listenAddress == nil { + return http.StatusBadRequest, fmt.Sprintf("Bad Request: \"%s\" is not an IP address.", existingListener.ListenAddress) + } + + server.DeleteAddr(listenAddress, existingListener.ListenPort, existingListener.ListenHostnameGlob) + + } else { + currentListenersThatCanKeepRunning = append(currentListenersThatCanKeepRunning, existingListener) + } + } + + for _, newListenerConfig := range listenerConfigs { + hasToBeAdded := true + for _, existingListener := range listenersByTenant[tenantId] { + if compareListenerConfigs(existingListener, newListenerConfig) { + hasToBeAdded = false + } + } + + if hasToBeAdded { + listenAddress := net.ParseIP(newListenerConfig.ListenAddress) + //fmt.Printf("str: %s, listenAddress: %s\n\n", newListenerConfig.ListenAddress, listenAddress) + if listenAddress == nil { + return http.StatusBadRequest, fmt.Sprintf("Bad Request: \"%s\" is not an IP address.", newListenerConfig.ListenAddress) + } + err := server.AddAddr( + listenAddress, + newListenerConfig.ListenPort, + newListenerConfig.ListenHostnameGlob, + newListenerConfig.ClientId, + newListenerConfig.HaProxyProxyProtocol, + newListenerConfig.BackEndService, + ) + + if err != nil { + if strings.Contains(err.Error(), "already in use") { + return http.StatusConflict, fmt.Sprintf("Port Conflict: Port %s is reserved or already in use", listenAddress) + } + + log.Printf("setListeners(): can't net.Listen(\"tcp\", \"%s\") because %s \n", listenAddress, err) + return http.StatusInternalServerError, "Unknown Listening Error" + } + + newListenersThatHaveToBeAdded = append(newListenersThatHaveToBeAdded, newListenerConfig) + } + } + + listenersByTenant[tenantId] = append(currentListenersThatCanKeepRunning, newListenersThatHaveToBeAdded...) + + return http.StatusOK, "ok" + +} + +func exportMetrics(config MetricsConfig, multiTenantServerMode bool, bandwidth <-chan tunnel.BandwidthMetric) { + metricsAPI := &PrometheusMetricsAPI{ + MultiTenantServerMode: multiTenantServerMode, + InboundByTenant: map[string]int64{}, + OutboundByTenant: map[string]int64{}, + InboundByService: map[string]int64{}, + OutboundByService: map[string]int64{}, + } + + go (func() { + for { + metric := <-bandwidth + if multiTenantServerMode { + tenantIdNodeId := strings.Split(metric.ClientId, ".") + if len(tenantIdNodeId) != 2 { + panic(fmt.Errorf("malformed metric.ClientId '%s', expected .", metric.ClientId)) + } + if metric.Inbound { + metricsAPI.InboundByTenant[tenantIdNodeId[0]] += int64(metric.Bytes) + } else { + metricsAPI.OutboundByTenant[tenantIdNodeId[0]] += int64(metric.Bytes) + } + } else { + if metric.Inbound { + metricsAPI.InboundByService[metric.Service] += int64(metric.Bytes) + } else { + metricsAPI.OutboundByService[metric.Service] += int64(metric.Bytes) + } + } + } + })() + + go (func() { + metricsServer := &http.Server{ + Addr: fmt.Sprintf(":%d", config.PrometheusMetricsAPIPort), + Handler: metricsAPI, + } + err := metricsServer.ListenAndServe() + panic(err) + })() +} + +func (s *PrometheusMetricsAPI) ServeHTTP(responseWriter http.ResponseWriter, request *http.Request) { + + getMillisecondsSinceUnixEpoch := func() int64 { + return time.Now().UnixNano() / int64(time.Millisecond) + } + + writeMetric := func(inbound map[string]int64, outbound map[string]int64, name, tag, desc string) { + timestamp := getMillisecondsSinceUnixEpoch() + responseWriter.Write([]byte(fmt.Sprintf("# HELP %s %s\n", name, desc))) + responseWriter.Write([]byte(fmt.Sprintf("# TYPE %s counter\n", name))) + for id, bytez := range inbound { + responseWriter.Write([]byte(fmt.Sprintf("%s{%s=\"%s\",direction=\"inbound\"} %d %d\n", name, tag, id, bytez, timestamp))) + } + for id, bytez := range outbound { + responseWriter.Write([]byte(fmt.Sprintf("%s{%s=\"%s\",direction=\"outbound\"} %d %d\n", name, tag, id, bytez, timestamp))) + } + } + + if strings.Contains(request.Header.Get("Accept"), "application/json") { + var bytez []byte + var err error + if s.MultiTenantServerMode { + bytez, err = json.MarshalIndent(PrometheusMetricsAPI{ + InboundByTenant: s.InboundByTenant, + OutboundByTenant: s.OutboundByTenant, + }, "", " ") + } else { + bytez, err = json.MarshalIndent(PrometheusMetricsAPI{ + InboundByService: s.InboundByService, + OutboundByService: s.OutboundByService, + }, "", " ") + } + + if err != nil { + log.Printf(fmt.Sprintf("500 internal server error: %s", err)) + http.Error(responseWriter, "500 internal server error", http.StatusInternalServerError) + return + } + + responseWriter.Header().Set("Content-Type", "application/json") + responseWriter.Write(bytez) + } else { + responseWriter.Header().Set("Content-Type", "text/plain; version=0.0.4") + + if s.MultiTenantServerMode { + writeMetric(s.InboundByTenant, s.OutboundByTenant, "bandwidth_by_tenant", "tenant", "bandwidth usage by tenant in bytes, excluding usage from control protocol.") + } else { + writeMetric(s.InboundByService, s.OutboundByService, "bandwidth_by_service", "service", "bandwidth usage by service in bytes.") + } + } +} + +func compareListenerConfigs(a, b ListenerConfig) bool { + return (a.ListenPort == b.ListenPort && + a.ListenAddress == b.ListenAddress && + a.ListenHostnameGlob == b.ListenHostnameGlob && + a.BackEndService == b.BackEndService && + a.ClientId == b.ClientId && + a.HaProxyProxyProtocol == b.HaProxyProxyProtocol) +} + +func (s *MultiTenantInternalAPI) ServeHTTP(responseWriter http.ResponseWriter, request *http.Request) { + switch path.Clean(request.URL.Path) { + case "/tenants": + if request.Method == "GET" || request.Method == "PUT" { + if request.Method == "PUT" { + if request.Header.Get("Content-Type") != "application/json" { + http.Error(responseWriter, "415 Unsupported Media Type: Content-Type must be application/json", http.StatusUnsupportedMediaType) + } else { + bodyBytes, err := ioutil.ReadAll(request.Body) + if err != nil { + http.Error(responseWriter, "500 Read Error", http.StatusInternalServerError) + return + } + var newTenants map[string]Tenant + err = json.Unmarshal(bodyBytes, &newTenants) + if err != nil { + http.Error(responseWriter, "422 Unprocessable Entity: Can't Parse JSON", http.StatusUnprocessableEntity) + return + } + tenantStatesMutex.Lock() + tenants = newTenants + tenantStatesMutex.Unlock() + } + } + + tenantStatesMutex.Lock() + bytes, err := json.Marshal(tenants) + tenantStatesMutex.Unlock() + if err != nil { + http.Error(responseWriter, "500 JSON Marshal Error", http.StatusInternalServerError) + return + } + responseWriter.Header().Set("Content-Type", "application/json") + responseWriter.Write(bytes) + + } else { + responseWriter.Header().Set("Allow", "GET, PUT") + http.Error(responseWriter, "405 Method Not Allowed, try GET or PUT", http.StatusMethodNotAllowed) + } + case "/ping": + if request.Method == "GET" { + fmt.Fprint(responseWriter, "pong") + } else { + responseWriter.Header().Set("Allow", "GET") + http.Error(responseWriter, "405 method not allowed, try GET", http.StatusMethodNotAllowed) + } + default: + http.Error(responseWriter, "404 Not Found, try /tenants or /ping", http.StatusNotFound) + } +} + +func (s *ManagementHttpHandler) ServeHTTP(responseWriter http.ResponseWriter, request *http.Request) { + + _, tenantId, err := validateCertificate(s.Domain, s.MultiTenantMode, request) + if err != nil { + http.Error(responseWriter, fmt.Sprintf("400 bad request: %s", err.Error()), http.StatusBadRequest) + return + } + if _, hasTenant := clientStatesByTenant[tenantId]; !hasTenant { + clientStatesByTenant[tenantId] = map[string]ClientState{} + } + if _, hasTenant := listenersByTenant[tenantId]; !hasTenant { + listenersByTenant[tenantId] = []ListenerConfig{} + } + + switch path.Clean(request.URL.Path) { + case "/clients": + if request.Method == "GET" { + clientStatesMutex.Lock() + + bytes, err := json.Marshal(clientStatesByTenant[tenantId]) + clientStatesMutex.Unlock() + if err != nil { + http.Error(responseWriter, "500 JSON Marshal Error", http.StatusInternalServerError) + return + } + responseWriter.Header().Set("Content-Type", "application/json") + responseWriter.Write(bytes) + + } else { + responseWriter.Header().Set("Allow", "GET") + http.Error(responseWriter, "405 Method Not Allowed, try GET", http.StatusMethodNotAllowed) + } + case "/tunnels": + if request.Method == "PUT" { + if request.Header.Get("Content-Type") != "application/json" { + http.Error(responseWriter, "415 Unsupported Media Type: Content-Type must be application/json", http.StatusUnsupportedMediaType) + } else { + bodyBytes, err := ioutil.ReadAll(request.Body) + if err != nil { + http.Error(responseWriter, "500 Read Error", http.StatusInternalServerError) + return + } + var listenerConfigs []ListenerConfig + err = json.Unmarshal(bodyBytes, &listenerConfigs) + if err != nil { + http.Error(responseWriter, "422 Unprocessable Entity: Can't Parse JSON", http.StatusUnprocessableEntity) + return + } + + if s.MultiTenantMode { + for _, listenerConfig := range listenerConfigs { + tenantIdNodeId := strings.Split(listenerConfig.ClientId, ".") + if len(tenantIdNodeId) != 2 { + http.Error( + responseWriter, + fmt.Sprintf( + "400 Bad Request: invalid ClientId '%s'. It needs to be in the form '.'", + listenerConfig.ClientId, + ), + http.StatusBadRequest, + ) + return + } + tenant, hasTenant := tenants[tenantIdNodeId[0]] + if !hasTenant { + http.Error( + responseWriter, + fmt.Sprintf("400 Bad Request: unknown tenantId '%s'", tenantIdNodeId[0]), + http.StatusBadRequest, + ) + } + isAuthorizedDomain := false + for _, tenantAuthorizedDomain := range tenant.AuthorizedDomains { + isSubdomain := strings.HasSuffix(listenerConfig.ListenHostnameGlob, fmt.Sprintf(".%s", tenantAuthorizedDomain)) + if (tenantAuthorizedDomain == listenerConfig.ListenHostnameGlob) || isSubdomain { + isAuthorizedDomain = true + break + } + } + if listenerConfig.ListenHostnameGlob != "" && !isAuthorizedDomain { + http.Error( + responseWriter, + fmt.Sprintf( + "400 Bad Request: ListenHostnameGlob '%s' is not covered by any of your authorized domains [%s]", + listenerConfig.ListenHostnameGlob, + strings.Join(stringSliceMap(tenant.AuthorizedDomains, func(x string) string { return fmt.Sprintf("'%s'", x) }), ", "), + ), + http.StatusBadRequest, + ) + } + + if listenerConfig.ListenHostnameGlob == "" { + isReservedPort := false + for _, tenantReservedPort := range tenant.ReservedPorts { + if listenerConfig.ListenPort == tenantReservedPort { + isReservedPort = true + break + } + } + if !isReservedPort { + http.Error( + responseWriter, + fmt.Sprintf( + "400 Bad Request: ListenHostnameGlob is empty and ListenPort '%d' is not one of your reserved ports [%s]", + listenerConfig.ListenPort, + strings.Join(intSlice2StringSlice(tenant.ReservedPorts), ", "), + ), + http.StatusBadRequest, + ) + } + } + } + } + + statusCode, errorMessage := setListeners(tenantId, listenerConfigs) + + if statusCode != 200 { + http.Error(responseWriter, errorMessage, statusCode) + return + } + + bytes, err := json.Marshal(listenerConfigs) + if err != nil { + http.Error(responseWriter, "500 JSON Marshal Error", http.StatusInternalServerError) + return + } + + responseWriter.Header().Set("Content-Type", "application/json") + responseWriter.Write(bytes) + } + } else { + responseWriter.Header().Set("Allow", "PUT") + http.Error(responseWriter, "405 Method Not Allowed, try PUT", http.StatusMethodNotAllowed) + } + case "/ping": + if request.Method == "GET" { + fmt.Fprint(responseWriter, "pong") + } else { + responseWriter.Header().Set("Allow", "GET") + http.Error(responseWriter, "405 method not allowed, try GET", http.StatusMethodNotAllowed) + } + default: + s.ControlHandler.ServeHTTP(responseWriter, request) + } +} From 3b0cd13006c361a2d3cda8c7289a3a1f797ff752 Mon Sep 17 00:00:00 2001 From: forest Date: Sat, 13 Feb 2021 19:27:50 -0600 Subject: [PATCH 06/36] WIP multitenant updates while working on greenhouse --- README.md | 6 +++--- main_server.go | 5 ++++- tunnel-lib/README.md | 2 +- 3 files changed, 8 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index fcd1a0a..ee06476 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,7 @@ Public Internet facing gateway (TCP reverse tunnel) for server.garden. -![](threshold.png) +![](readme/splash.png) This project was originally forked from https://github.com/koding/tunnel @@ -13,7 +13,7 @@ This repository only includes the application that does the tunneling part. It See the usage example folder for a basic test. -![Diagram](readme/Diagram.png) +![Diagram](readme/diagram.png) ### How it is intended to be used: @@ -120,4 +120,4 @@ go build -o tunnel -tags netgo # see: https://stackoverflow.com/questions/36279253/go-compiled-binary-wont-run-in-an-alpine-docker-container-on-ubuntu-host docker build -t sequentialread/tunnel:0.0.1 . -``` \ No newline at end of file +``` diff --git a/main_server.go b/main_server.go index 7bb8adf..910ba4b 100644 --- a/main_server.go +++ b/main_server.go @@ -373,6 +373,7 @@ func exportMetrics(config MetricsConfig, multiTenantServerMode bool, bandwidth < metricsAPI.OutboundByTenant[tenantIdNodeId[0]] += int64(metric.Bytes) } } else { + // TODO shouldn't this be done on the client side only ?? if metric.Inbound { metricsAPI.InboundByService[metric.Service] += int64(metric.Bytes) } else { @@ -392,6 +393,7 @@ func exportMetrics(config MetricsConfig, multiTenantServerMode bool, bandwidth < })() } +// TODO move this to the management API / to the client side. func (s *PrometheusMetricsAPI) ServeHTTP(responseWriter http.ResponseWriter, request *http.Request) { getMillisecondsSinceUnixEpoch := func() int64 { @@ -410,7 +412,7 @@ func (s *PrometheusMetricsAPI) ServeHTTP(responseWriter http.ResponseWriter, req } } - if strings.Contains(request.Header.Get("Accept"), "application/json") { + if strings.Contains(request.Header.Get("Accept"), "application/json") && !strings.Contains(request.Header.Get("Accept"), "text/plain") { var bytez []byte var err error if s.MultiTenantServerMode { @@ -419,6 +421,7 @@ func (s *PrometheusMetricsAPI) ServeHTTP(responseWriter http.ResponseWriter, req OutboundByTenant: s.OutboundByTenant, }, "", " ") } else { + // TODO this should probably only be supported on the client side bytez, err = json.MarshalIndent(PrometheusMetricsAPI{ InboundByService: s.InboundByService, OutboundByService: s.OutboundByService, diff --git a/tunnel-lib/README.md b/tunnel-lib/README.md index 8f5fbc2..b68f7c1 100644 --- a/tunnel-lib/README.md +++ b/tunnel-lib/README.md @@ -1,4 +1,4 @@ -# Tunnel [![GoDoc](http://img.shields.io/badge/go-documentation-blue.svg?style=flat-square)](http://godoc.org/git.sequentialread.com/forest/tunnel) [![Go Report Card](https://goreportcard.com/badge/git.sequentialread.com/forest/tunnel)](https://goreportcard.com/report/git.sequentialread.com/forest/tunnel) [![Build Status](http://img.shields.io/travis/koding/tunnel.svg?style=flat-square)](https://travis-ci.org/koding/tunnel) +# Tunnel Tunnel is a server/client package that enables to proxy public connections to your local machine over a tunnel connection from the local machine to the From 2393bd717cf31377bf6c02d5f392aaf35859b337 Mon Sep 17 00:00:00 2001 From: forest Date: Sat, 13 Feb 2021 19:29:05 -0600 Subject: [PATCH 07/36] update diagram and add GPL --- LICENSE.md | 231 +++++++++++++++++++++++++++++ readme/Diagram.png | Bin 23314 -> 0 bytes readme/Diagram.svg | 2 - readme/diagram.drawio | 1 + readme/diagram.png | Bin 0 -> 30117 bytes threshold.png => readme/splash.png | Bin 6 files changed, 232 insertions(+), 2 deletions(-) create mode 100644 LICENSE.md delete mode 100644 readme/Diagram.png delete mode 100644 readme/Diagram.svg create mode 100644 readme/diagram.drawio create mode 100644 readme/diagram.png rename threshold.png => readme/splash.png (100%) diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000..b081af3 --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,231 @@ +GNU GENERAL PUBLIC LICENSE +================== + +Version 3, 29 June 2007 + + +Preamble +--------------------- + +The GNU General Public License is a free, copyleft license for software and other kinds of works. + +The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. + +When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. + +To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. + +For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. + +Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. + +For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. + +Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. + +Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. + +The precise terms and conditions for copying, distribution and modification follow. + +TERMS AND CONDITIONS +==================== + +## 0. Definitions. +-------------------------------- + + +“This License” refers to version 3 of the GNU General Public License. + +“Copyright” also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. + +“The Program” refers to any copyrightable work licensed under this License. Each licensee is addressed as “you”. “Licensees” and “recipients” may be individuals or organizations. + +To “modify” a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a “modified version” of the earlier work or a work “based on” the earlier work. + +A “covered work” means either the unmodified Program or a work based on the Program. + +To “propagate” a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. + +To “convey” a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. + +An interactive user interface displays “Appropriate Legal Notices” to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. + +## 1. Source Code. +-------------------------------- + + +The “source code” for a work means the preferred form of the work for making modifications to it. “Object code” means any non-source form of a work. + +A “Standard Interface” means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. + +The “System Libraries” of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A “Major Component”, in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. + +The “Corresponding Source” for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. + +The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. + +The Corresponding Source for a work in source code form is that same work. + +## 2. Basic Permissions. +---------------------------- + + +All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. + +You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. + +Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. + +## 3. Protecting Users' Legal Rights From Anti-Circumvention Law. +-------------------------------- + +No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. + +When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. + +## 4. Conveying Verbatim Copies. +-------------------------------- + +You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. + +You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. + +## 5. Conveying Modified Source Versions. +-------------------------------- + +You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: + + - a) The work must carry prominent notices stating that you modified it, and giving a relevant date. + - b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to “keep intact all notices”. + - c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. + - d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. + +A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an “aggregate” if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. + +## 6. Conveying Non-Source Forms. +-------------------------------- + +You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: + + - a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. + - b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. + - c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. + - d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. + - e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. + +A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. + +A “User Product” is either (1) a “consumer product”, which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, “normally used” refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. + +“Installation Information” for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. + +If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). + +The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. + +Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. + +## 7. Additional Terms. +-------------------------------- + +“Additional permissions” are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. + +When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. + +Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: + + - a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or + - b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or + - c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or + - d) Limiting the use for publicity purposes of names of licensors or authors of the material; or + - e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or + - f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. + +All other non-permissive additional terms are considered “further restrictions” within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. + +If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. + +Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. + +## 8. Termination. +-------------------------------- + +You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). + +However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. + +Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. + +Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. + +## 9. Acceptance Not Required for Having Copies. +-------------------------------- + +You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. + + +## 10. Automatic Licensing of Downstream Recipients. +-------------------------------- + +Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. + +An “entity transaction” is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. + +You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. + +## 11. Patents. +-------------------------------- + +A “contributor” is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's “contributor version”. + +A contributor's “essential patent claims” are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, “control” includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. + +Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. + +In the following three paragraphs, a “patent license” is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To “grant” such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. + +If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. “Knowingly relying” means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. + +If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. + +A patent license is “discriminatory” if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. + +Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. + +## 12. No Surrender of Others' Freedom. +-------------------------------- + +If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. + +## 13. Use with the GNU Affero General Public License. +-------------------------------- + +Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. + + +## 14. Revised Versions of this License. +-------------------------------- + +The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. + +If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. + +Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. + +## 15. Disclaimer of Warranty. +-------------------------------- + +THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + +## 16. Limitation of Liability. +-------------------------------- + +IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + +## 17. Interpretation of Sections 15 and 16. +-------------------------------- + +If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. \ No newline at end of file diff --git a/readme/Diagram.png b/readme/Diagram.png deleted file mode 100644 index 63f75e80f870b85f78f8f4764e5b325e07246815..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 23314 zcmd43XINBCw=HTSOU_vo6j}rUK|q3JXmZmkND>f`Bw0a{l5>)7vcv{jBudU1B}&d9 zIp>^jwXg4Y_P%$Y=boR3KRn&5*Q!~ws%FiaV~iD`rXoj(Pltcy$`wKdd1=^{E7uTL zu3UA)#RlIz%l$lX<;txq3epmAr-Zd?7dYHB?x5N(5+}VKm8EV-LF(0W8)E))`(r9eCR3-^oiPM+o;-1NozI{o?ATA8jMx0h-%oz%=tr{Vd~)~x$nP3ieJoN&If zU~PI$^-8kpd90PW#oHX&(n5YyXZiLE)t{1v|N1D~x|YHiZ&do>Eoit*I0~BjYBZem zd!Fvc7Ea~*tXNqVy228oP8v`IQ)Ro@fZ)^6G0`h^YF=18bes{| zj76fK;n??B-ZXM}e}f7zDgIWuF(>qfdHuAI=N*&{JpBQ9x=wC1tql7d1#g^Esc3~4 zoBcrewa?+d_KM&Ft8F9{CKT$Mu?n~fwMJ2@LWHnnI-{M@D>PUIvztt5xkoo!I^a_H zV*bfT8Z;&nt}DI7lK60=$Z?a3c^*hudY$Q8USz+Rz{P1gcACkCH$@q_m|}NH*r~xh z$4xwVBX`X;0^~+(%wDCup1DZqdPXapX@r===AP$VNoHuaI+yfE=Mn)`BJSPr#W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supported by viewer]
Home Network
[Not supported by viewer]
 Server
[Not supported by viewer]
 Cloud Instance
[Not supported by viewer]
 tunnel server
 tunnel server
TLS
[Not supported by viewer]
 tunnel client
 tunnel client
HTTPS
HTTPS
HTTPS
HTTPS
TLS
[Not supported by viewer]
Public
Internet
[Not supported by viewer]
TLS
[Not supported by viewer]
TLS
[Not supported by viewer]
Router
[Not supported by viewer]
server software
server software
TLS
[Not supported by viewer]
TLS Cert
[Not supported by viewer]
\ No newline at end of file diff --git a/readme/diagram.drawio b/readme/diagram.drawio new file mode 100644 index 0000000..9b59258 --- /dev/null +++ b/readme/diagram.drawio @@ -0,0 +1 @@ +7VvbcqM4EP0aP44LEAh4nDjOJFPZ2dR6qnbnaYqLsNlg5AU5TubrVwLJXCRsbEOSmkr8EGgJIbqPuk83YgJm6+cvmbdZ/YFDlEwMLXyegOuJYei6Aek/JnkpJbZtloJlFoe8UyVYxL8QF2pcuo1DlDc6EowTEm+awgCnKQpIQ+ZlGd41u0U4ad514y2RJFgEXiJL/45DsiqljqVV8lsUL1fizrrGW9ae6MwF+coL8a4mAvMJmGUYk/Jo/TxDCVOe0Et53U1H635iGUpJnwt+2YZzt9ju4J3pPnz9+i3CP51PfJQnL9nyB+aTJS9CAxnepiFig2gTcLVbxQQtNl7AWnfU5lS2IuuEnun0MPTyVdGXnURxksxwgrNiIBB6yIkCKs9Jhh9RrQUGDvIj2iI/k5ggygh6ron4M35BeI1I9kK7iFaH65sDzuSnu8p6hrDRqm45cZ3HEbPcD10plR5wvZ6gY+MVdYz00EK2SscutIEHh9GxaVsNHet6TyUb7lhKBgolw4QwdcVP7IZJvEyLBvjfli25qwRFpDqjR0v+v7gqwlQ7zK0IBVYdgaaZM9eVr50leBvSixYoe4qp8QztIcNP1H9lYlQ/a9+HPmx5K0lczFtIW3ihdiKSkVOcohYiuEg8fPHI4IoZOqYu7jMXr+MwZCNfNWHYxBmd5IJPQJzX0KVpAEDYxKkKxiMscEPGnm6qsDcW9MxO6B0CkTnT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56K0fTojg8VfH0YWWeynAmMLUOXfMNysFT9sFTOz5fgxXhFZcL5hAshYPv9QnOm0ylE3bw3t5s8sSHZUbE4v/XTUkAarznwk9KMm9CJLGiIQQUvQhpfGSBdi2XIbg8Lm9eMFKSBXpwfgueK4cia1wiB0YNPZaLo9totr8+vzuW5fquu8K6oLujeSfXiYATyMMaCH0YFjNKnuQD7GsKatgNmKl+O5mW4qfBh+7K8H/P7CW9LYGXQyAkfak3FsV09FjZterbWBqL5Vo9SJiofXdmsMwKilF2uGzKldRUnGHI1RyzsSxd4L6rYjsqNPK9n1sjK071impfVKepwAFW9S36AMbUPJMK9bhgaqjYDyAiu/E2hssNQOGUBd57Q09hNu/QHnMYmxMhDctzr4mBC8VkSKci8TLlfubP/JhaYyp3AU6+cl+zRkSn1mHKBpiNje6HyaeJtytJOrbCeszCZXNMQrpnqt1FGY3xzL/Ko6WptUHtvecHbiOrWab5qn7v58ONYnEH6U9hl9c9/X2R3RKouY527Zgc1xgN0v0x6KPgjEf9DXceirWMBD0FfTFMv//ZZmzR77BmseiweiS9zV/gUQcOvJsTjufv8j76O5wIuZPb2Y+a69mAWH8WJWe7v6yF7Mkt/WS6hja3zTnyOcvEAtwQyEJxdbaGuWhApLtlU+3GdG56WGEGoazaQk1154cm1G9XT+N0aC4qWY9MkF+27H51O+4KOQvTtRb9N3OqltzzhgdRVKDy78V4UL6Lfj+8xUY+iU4mj2sM4DD02Ld3LTR/Ty88nbltBv7+3QtJubywP9CQYWrWa7ZiRXAcAwuSY9rT4bL31u9fE9mP8P \ No newline at end of file diff --git a/readme/diagram.png b/readme/diagram.png new file mode 100644 index 0000000000000000000000000000000000000000..6421d903f99537a645eab0715dd9b6eb69853392 GIT binary patch literal 30117 zcmd42c{tQv+y|@@DqBQCx`mQ#V;M7qFbl>ujAc}6jKMH7mNCO1D%rPEC|QbRq-=#` zD{E0`5wa%{vKGqrp1GIjdH#8?_uu!rCfCgG{LVSwefgYItc?{~V6Ws}E-o$sGgE{u z7u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I~w zg;Jj;uhfy;T3gk7wa0g#3ZH3v&U>eQ*NwvHm%NJKJfHq{v_idjD= zltbRBI|TN4m`GG2#b-cXx;g&?BXl1`p?oNdwkvNzK$m_&Qm`Ezg(I9a(R0mn&RjFk zDcM=_HyIR60iLJ2a(+Wo-Zi$P{#80;PG-F0k;>Z2I%5q9^M&bJtEN3>nj=4DegYGNiAEF=GC!wMBa@(qk$(WyL>=|9fOE@`j|@Qd@y>E%a_2dx~@`aS)|kbMnBzNYH76K*2#blY-fE0p zGJ1#rf5*%;?_!`Cj~H+!ZVVhXuyu#f&K`li$FQ& z2IzOx9pi8Q8(%V|bJ<+JJaS}N3e*Xdd&|Ks-|^ep}O zk{X**8hVk|h!DxT(_xJbQ7EQsbG+pkx=(c)8xbV Date: Thu, 25 Mar 2021 17:17:22 -0500 Subject: [PATCH 08/36] updates for greenhouse --- README.md | 5 +++++ go.mod | 2 +- main_client.go | 2 +- main_server.go | 21 +++++++++------------ tunnel-lib/client.go | 2 +- tunnel-lib/proxy.go | 2 +- tunnel-lib/server.go | 2 +- tunnel-lib/tcpproxy.go | 2 +- tunnel-lib/util.go | 2 +- 9 files changed, 21 insertions(+), 19 deletions(-) diff --git a/README.md b/README.md index ee06476..976468b 100644 --- a/README.md +++ b/README.md @@ -15,6 +15,11 @@ See the usage example folder for a basic test. ![Diagram](readme/diagram.png) +This diagram was created with https://app.diagrams.net/. +To edit it, download the diagram file and edit it with the https://app.diagrams.net/ web application, or you may run the application from [source](https://github.com/jgraph/drawio) if you wish. + + + ### How it is intended to be used: 1. An automated tool creates a cloud instance and installs and configures the tunnel server on it. diff --git a/go.mod b/go.mod index 3208112..b5eff1a 100644 --- a/go.mod +++ b/go.mod @@ -1,4 +1,4 @@ -module git.sequentialread.com/forest/tunnel +module git.sequentialread.com/forest/threshold go 1.14 diff --git a/main_client.go b/main_client.go index 8c8fc3a..4931e50 100644 --- a/main_client.go +++ b/main_client.go @@ -17,7 +17,7 @@ import ( "strings" "time" - tunnel "git.sequentialread.com/forest/tunnel/tunnel-lib" + tunnel "git.sequentialread.com/forest/threshold/tunnel-lib" ) type ClientConfig struct { diff --git a/main_server.go b/main_server.go index 910ba4b..137c23b 100644 --- a/main_server.go +++ b/main_server.go @@ -18,7 +18,7 @@ import ( "sync" "time" - tunnel "git.sequentialread.com/forest/tunnel/tunnel-lib" + tunnel "git.sequentialread.com/forest/threshold/tunnel-lib" ) type ServerConfig struct { @@ -79,7 +79,8 @@ type PrometheusMetricsAPI struct { } type Tenant struct { - ReservedPorts []int + PortStart int + PortEnd int AuthorizedDomains []string } @@ -472,6 +473,7 @@ func (s *MultiTenantInternalAPI) ServeHTTP(responseWriter http.ResponseWriter, r var newTenants map[string]Tenant err = json.Unmarshal(bodyBytes, &newTenants) if err != nil { + log.Printf("422 Unprocessable Entity: Can't Parse JSON: %+v\n", err) http.Error(responseWriter, "422 Unprocessable Entity: Can't Parse JSON", http.StatusUnprocessableEntity) return } @@ -492,7 +494,8 @@ func (s *MultiTenantInternalAPI) ServeHTTP(responseWriter http.ResponseWriter, r responseWriter.Write(bytes) } else { - responseWriter.Header().Set("Allow", "GET, PUT") + responseWriter.Header().Add("Allow", "PUT") + responseWriter.Header().Add("Allow", "GET") http.Error(responseWriter, "405 Method Not Allowed, try GET or PUT", http.StatusMethodNotAllowed) } case "/ping": @@ -599,20 +602,14 @@ func (s *ManagementHttpHandler) ServeHTTP(responseWriter http.ResponseWriter, re } if listenerConfig.ListenHostnameGlob == "" { - isReservedPort := false - for _, tenantReservedPort := range tenant.ReservedPorts { - if listenerConfig.ListenPort == tenantReservedPort { - isReservedPort = true - break - } - } + isReservedPort := (listenerConfig.ListenPort >= tenant.PortStart && listenerConfig.ListenPort <= tenant.PortEnd) if !isReservedPort { http.Error( responseWriter, fmt.Sprintf( - "400 Bad Request: ListenHostnameGlob is empty and ListenPort '%d' is not one of your reserved ports [%s]", + "400 Bad Request: ListenHostnameGlob is empty and ListenPort '%d' is not one of your reserved ports %d..%d", listenerConfig.ListenPort, - strings.Join(intSlice2StringSlice(tenant.ReservedPorts), ", "), + tenant.PortStart, tenant.PortEnd, ), http.StatusBadRequest, ) diff --git a/tunnel-lib/client.go b/tunnel-lib/client.go index 07ec011..515a61e 100644 --- a/tunnel-lib/client.go +++ b/tunnel-lib/client.go @@ -12,7 +12,7 @@ import ( "sync/atomic" "time" - "git.sequentialread.com/forest/tunnel/tunnel-lib/proto" + "git.sequentialread.com/forest/threshold/tunnel-lib/proto" "github.com/hashicorp/yamux" ) diff --git a/tunnel-lib/proxy.go b/tunnel-lib/proxy.go index aa8975a..7447bf5 100644 --- a/tunnel-lib/proxy.go +++ b/tunnel-lib/proxy.go @@ -7,7 +7,7 @@ import ( "strings" "sync" - "git.sequentialread.com/forest/tunnel/tunnel-lib/proto" + "git.sequentialread.com/forest/threshold/tunnel-lib/proto" ) // ProxyFunc is responsible for forwarding a remote connection to local server and writing the response back. diff --git a/tunnel-lib/server.go b/tunnel-lib/server.go index 58f2fdf..5e44ff8 100644 --- a/tunnel-lib/server.go +++ b/tunnel-lib/server.go @@ -16,7 +16,7 @@ import ( "sync" "time" - "git.sequentialread.com/forest/tunnel/tunnel-lib/proto" + "git.sequentialread.com/forest/threshold/tunnel-lib/proto" "github.com/hashicorp/yamux" ) diff --git a/tunnel-lib/tcpproxy.go b/tunnel-lib/tcpproxy.go index ea9011f..ce887e3 100644 --- a/tunnel-lib/tcpproxy.go +++ b/tunnel-lib/tcpproxy.go @@ -4,7 +4,7 @@ import ( "log" "net" - "git.sequentialread.com/forest/tunnel/tunnel-lib/proto" + "git.sequentialread.com/forest/threshold/tunnel-lib/proto" ) // TCPProxy forwards TCP streams. diff --git a/tunnel-lib/util.go b/tunnel-lib/util.go index 94ed5d1..40f0e78 100644 --- a/tunnel-lib/util.go +++ b/tunnel-lib/util.go @@ -7,7 +7,7 @@ import ( "sync" "time" - "git.sequentialread.com/forest/tunnel/tunnel-lib/proto" + "git.sequentialread.com/forest/threshold/tunnel-lib/proto" "github.com/cenkalti/backoff" ) From 45ebe469d871eaf1022b775f3714723df0aa4b6b Mon Sep 17 00:00:00 2001 From: forest Date: Thu, 25 Mar 2021 18:19:19 -0500 Subject: [PATCH 09/36] working on setting up greenhouse integration for client --- main_client.go | 90 +++++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 74 insertions(+), 16 deletions(-) diff --git a/main_client.go b/main_client.go index 4931e50..15e4d2f 100644 --- a/main_client.go +++ b/main_client.go @@ -14,6 +14,7 @@ import ( "os" "path" "path/filepath" + "regexp" "strings" "time" @@ -21,17 +22,19 @@ import ( ) type ClientConfig struct { - DebugLog bool - ClientId string - MultiTenantSchedulerServer string - ServerAddr string - Servers []string - ServiceToLocalAddrMap *map[string]string - CaCertificateFilesGlob string - ClientTlsKeyFile string - ClientTlsCertificateFile string - AdminUnixSocket string - Metrics MetricsConfig + DebugLog bool + ClientId string + GreenhouseDomain string + GreenhouseAPIKey string + GreenhouseThresholdPort int + ServerAddr string + Servers []string + ServiceToLocalAddrMap *map[string]string + CaCertificateFilesGlob string + ClientTlsKeyFile string + ClientTlsCertificateFile string + AdminUnixSocket string + Metrics MetricsConfig } type ClientServer struct { @@ -62,6 +65,10 @@ func runClient(configFileName *string) { log.Fatalf("runClient(): can't json.Unmarshal(configBytes, &config) because %s \n", err) } + if config.GreenhouseThresholdPort == 0 { + config.GreenhouseThresholdPort = 9056 + } + clientServers = []ClientServer{} makeServer := func(hostPort string) ClientServer { serverURLString := fmt.Sprintf("https://%s", hostPort) @@ -75,14 +82,56 @@ func runClient(configFileName *string) { } } - if config.MultiTenantSchedulerServer != "" { + if config.GreenhouseDomain != "" { if config.ServerAddr != "" { - log.Fatal("config contains both MultiTenantSchedulerServer and ServerAddr, only use one or the other") + log.Fatal("config contains both GreenhouseDomain and ServerAddr, only use one or the other") } if config.Servers != nil && len(config.Servers) > 0 { - log.Fatal("config contains both MultiTenantSchedulerServer and Servers, only use one or the other") + log.Fatal("config contains both GreenhouseDomain and Servers, only use one or the other") + } + if config.GreenhouseAPIKey == "" { + log.Fatal("config contains GreenhouseDomain but does not contain GreenhouseAPIKey, use both or niether") + } + + greenhouseClient := http.Client{Timeout: time.Second * 10} + greenhouseURL := fmt.Sprintf("https://%s/api/thresholdservers", config.GreenhouseDomain) + request, err := http.NewRequest("GET", greenhouseURL, nil) + if err != nil { + log.Fatal("invalid GreenhouseDomain '%s', can't create http request for %s", config.GreenhouseDomain, greenhouseURL) + } + request.Header.Add("Authorization", fmt.Sprintf("Bearer %s", config.GreenhouseAPIKey)) + + response, err := greenhouseClient.Do(request) + if err != nil || response.StatusCode != 200 { + if err == nil { + if response.StatusCode == 401 { + log.Fatalf("bad or expired GreenhouseAPIKey, recieved HTTP 401 Unauthorized from Greenhouse server %s", greenhouseURL) + } else { + log.Fatalf("server error: recieved HTTP %d from Greenhouse server %s", response.StatusCode, greenhouseURL) + } + } + log.Printf("can't reach %s, falling back to DNS lookup...\n", greenhouseURL) + ips, err := net.LookupIP(config.GreenhouseDomain) + if err != nil { + log.Fatal("Failed to lookup GreenhouseDomain '%s'", config.GreenhouseDomain) + } + for _, ip := range ips { + clientServers = append(clientServers, makeServer(fmt.Sprintf("%s:%d", ip, config.GreenhouseThresholdPort))) + } + } else { + responseBytes, err := ioutil.ReadAll(response.Body) + if err != nil { + log.Fatal("http read error GET '%s'", greenhouseURL) + } + var ipPorts []string + err = json.Unmarshal(responseBytes, &ipPorts) + if err != nil { + log.Fatal("http read error GET '%s'", greenhouseURL) + } + for _, serverHostPort := range ipPorts { + clientServers = append(clientServers, makeServer(serverHostPort)) + } } - // TODO Grab server host/ports from greenhouse } else if config.Servers != nil && len(config.Servers) > 0 { if config.ServerAddr != "" { @@ -98,7 +147,16 @@ func runClient(configFileName *string) { serviceToLocalAddrMap = config.ServiceToLocalAddrMap configToLog, _ := json.MarshalIndent(config, "", " ") - log.Printf("theshold client is starting up using config:\n%s\n", string(configToLog)) + configToLogString := string(configToLog) + + configToLogString = regexp.MustCompile( + `("GreenhouseAPIKey": ")[^"]+(",)`, + ).ReplaceAllString( + configToLogString, + "$1******$2", + ) + + log.Printf("theshold client is starting up using config:\n%s\n", configToLogString) dialFunction := net.Dial From 3ff3cc48430ea30967fd107dde3015bec576a506 Mon Sep 17 00:00:00 2001 From: forest Date: Mon, 29 Mar 2021 12:38:05 -0500 Subject: [PATCH 10/36] scrape hostname from HTTP request --- main_client.go | 15 +++++++++++++-- main_server.go | 6 +++++- tunnel-lib/server.go | 19 ++++++++++++++----- tunnel-lib/virtualaddr.go | 32 +++++++++++++++++++++++--------- 4 files changed, 55 insertions(+), 17 deletions(-) diff --git a/main_client.go b/main_client.go index 15e4d2f..0f83d51 100644 --- a/main_client.go +++ b/main_client.go @@ -113,7 +113,7 @@ func runClient(configFileName *string) { log.Printf("can't reach %s, falling back to DNS lookup...\n", greenhouseURL) ips, err := net.LookupIP(config.GreenhouseDomain) if err != nil { - log.Fatal("Failed to lookup GreenhouseDomain '%s'", config.GreenhouseDomain) + log.Fatalf("Failed to lookup GreenhouseDomain '%s'", config.GreenhouseDomain) } for _, ip := range ips { clientServers = append(clientServers, makeServer(fmt.Sprintf("%s:%d", ip, config.GreenhouseThresholdPort))) @@ -165,7 +165,15 @@ func runClient(configFileName *string) { log.Fatal(err) } - commonName := cert.Leaf.Subject.CommonName + parsedCert, err := x509.ParseCertificate(cert.Certificate[0]) + if err != nil { + log.Fatal(err) + } + + if parsedCert == nil { + log.Fatalf("parsedCert is nil (%s)", config.ClientTlsCertificateFile) + } + commonName := parsedCert.Subject.CommonName clientIdDomain := strings.Split(commonName, "@") if len(clientIdDomain) != 2 { @@ -253,6 +261,9 @@ func runClient(configFileName *string) { } log.Print("runClient(): the client should be running now\n") + + blockForever := make(chan int) + <-blockForever } func runClientAdminApi(config ClientConfig) { diff --git a/main_server.go b/main_server.go index 137c23b..d443ea5 100644 --- a/main_server.go +++ b/main_server.go @@ -107,6 +107,7 @@ func runServer(configFileName *string) { log.Printf("threshold server is starting up using config:\n%s\n", string(configToLog)) clientStateChangeChannel := make(chan *tunnel.ClientStateChange) + listenersByTenant = map[string][]ListenerConfig{} var metricChannel chan tunnel.BandwidthMetric = nil @@ -119,6 +120,7 @@ func runServer(configFileName *string) { tunnelServerConfig := &tunnel.ServerConfig{ StateChanges: clientStateChangeChannel, ValidateCertificate: validateCertificate, + MultitenantMode: config.MultiTenantMode, Bandwidth: metricChannel, Domain: config.Domain, DebugLog: config.DebugLog, @@ -580,6 +582,7 @@ func (s *ManagementHttpHandler) ServeHTTP(responseWriter http.ResponseWriter, re fmt.Sprintf("400 Bad Request: unknown tenantId '%s'", tenantIdNodeId[0]), http.StatusBadRequest, ) + return } isAuthorizedDomain := false for _, tenantAuthorizedDomain := range tenant.AuthorizedDomains { @@ -593,7 +596,8 @@ func (s *ManagementHttpHandler) ServeHTTP(responseWriter http.ResponseWriter, re http.Error( responseWriter, fmt.Sprintf( - "400 Bad Request: ListenHostnameGlob '%s' is not covered by any of your authorized domains [%s]", + `400 Bad Request: ListenHostnameGlob '%s' is not covered by any of your authorized domains [%s]. + If you are trying to use a reserved port, leave ListenHostnameGlob blank.`, listenerConfig.ListenHostnameGlob, strings.Join(stringSliceMap(tenant.AuthorizedDomains, func(x string) string { return fmt.Sprintf("'%s'", x) }), ", "), ), diff --git a/tunnel-lib/server.go b/tunnel-lib/server.go index 5e44ff8..f3b0cd2 100644 --- a/tunnel-lib/server.go +++ b/tunnel-lib/server.go @@ -73,8 +73,10 @@ type Server struct { bandwidth chan<- BandwidthMetric + multitenantMode bool + // see ServerConfig.ValidateCertificate comment - validateCertificate func(domain string, request *http.Request) (identifier string, tenantId string, err error) + validateCertificate func(domain string, multitenantMode bool, request *http.Request) (identifier string, tenantId string, err error) // yamuxConfig is passed to new yamux.Session's yamuxConfig *yamux.Config @@ -116,6 +118,8 @@ type ServerConfig struct { // the tenantId it returns will be `` or "" ValidateCertificate func(domain string, multiTenantMode bool, request *http.Request) (identifier string, tenantId string, err error) + MultitenantMode bool + // YamuxConfig defines the config which passed to every new yamux.Session. If nil // yamux.DefaultConfig() is used. YamuxConfig *yamux.Config @@ -146,6 +150,8 @@ func NewServer(cfg *ServerConfig) (*Server, error) { virtualAddrs: newVirtualAddrs(opts), controls: newControls(), states: make(map[string]ClientState), + multitenantMode: cfg.MultitenantMode, + validateCertificate: cfg.ValidateCertificate, bandwidth: cfg.Bandwidth, stateCh: cfg.StateChanges, domain: cfg.Domain, @@ -166,7 +172,9 @@ func (s *Server) ServeHTTP(responseWriter http.ResponseWriter, request *http.Req // going to infer and call the respective path handlers. switch fmt.Sprintf("%s/", path.Clean(request.URL.Path)) { case proto.ControlPath: - s.checkConnect(s.controlHandler).ServeHTTP(responseWriter, request) + s.checkConnect(func(w http.ResponseWriter, r *http.Request) error { + return s.controlHandler(w, r) + }).ServeHTTP(responseWriter, request) case "/ping/": if request.Method == "GET" { fmt.Fprint(responseWriter, "pong!") @@ -391,7 +399,7 @@ func (s *Server) dial(identifier string, service string) (net.Conn, error) { // tunnel TCP connections. func (s *Server) controlHandler(w http.ResponseWriter, r *http.Request) (ctErr error) { - clientId, tenantId, err := s.validateCertificate(s.domain, r) + clientId, tenantId, err := s.validateCertificate(s.domain, s.multitenantMode, r) fmt.Println(tenantId) if err != nil { return err @@ -694,6 +702,7 @@ func copyHeader(dst, src http.Header) { // checkConnect checks whether the incoming request is HTTP CONNECT method. func (s *Server) checkConnect(fn func(w http.ResponseWriter, r *http.Request) error) http.Handler { + server := s return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Method != "CONNECT" { http.Error(w, "405 must CONNECT\n", http.StatusMethodNotAllowed) @@ -703,9 +712,9 @@ func (s *Server) checkConnect(fn func(w http.ResponseWriter, r *http.Request) er if err := fn(w, r); err != nil { log.Printf("Server.checkConnect(): Handler err: %v\n", err.Error()) - identifier, _, err := s.validateCertificate(s.domain, r) + identifier, _, err := server.validateCertificate(server.domain, server.multitenantMode, r) if err == nil { - s.onDisconnect(identifier, err) + server.onDisconnect(identifier, err) } http.Error(w, err.Error(), 502) diff --git a/tunnel-lib/virtualaddr.go b/tunnel-lib/virtualaddr.go index f6626ed..2b02b7c 100644 --- a/tunnel-lib/virtualaddr.go +++ b/tunnel-lib/virtualaddr.go @@ -46,13 +46,20 @@ type vaddrStorage struct { // ports map[int]*listener // port-based routing: maps port number to identifier // ips map[string]*listener // ip-based routing: maps ip address to identifier + httpHostRegex *regexp.Regexp + dotRegex *regexp.Regexp + globRegex *regexp.Regexp + mu sync.RWMutex } func newVirtualAddrs(opts *vaddrOptions) *vaddrStorage { return &vaddrStorage{ - vaddrOptions: opts, - listeners: make(map[string]*listener), + vaddrOptions: opts, + listeners: make(map[string]*listener), + httpHostRegex: regexp.MustCompile("[A-Z]+ [^ ]+ HTTP[^\n]+\n([A-Za-z0-9-]+: [^\n]+\n)*(H|h)ost: ([^\n]+)\n"), + dotRegex: regexp.MustCompile(`\.`), + globRegex: regexp.MustCompile(`\*+`), // ports: make(map[int]*listener), // ips: make(map[string]*listener), } @@ -258,7 +265,7 @@ func (vaddr *vaddrStorage) getListenerInfo(conn net.Conn) (*ListenerInfo, string //log.Printf("pre getHostnameFromSNI ") - connectionHeader := make([]byte, 1024) + connectionHeader := make([]byte, 4096) n, err := conn.Read(connectionHeader) if err != nil && err != io.EOF { log.Printf("vaddrStorage.getListenerInfo(): failed to read header for connection %q: %s", conn.LocalAddr(), err) @@ -268,10 +275,16 @@ func (vaddr *vaddrStorage) getListenerInfo(conn net.Conn) (*ListenerInfo, string hostname, err := getHostnameFromSNI(connectionHeader[:n]) // This will happen every time someone connects with a non-TLS protocol. - // Its not a big deal, we can ignore it. - // if err != nil { - // log.Printf("vaddrStorage.getListenerInfo(): failed to get SNI for connection %q: %s\n", conn.LocalAddr(), err) - // } + if err != nil { + submatches := vaddr.httpHostRegex.FindSubmatch(connectionHeader[:n]) + //log.Printf("--\n%d\n--\n", len(submatches)) + if submatches != nil && len(submatches) == 4 { + //log.Printf("---\n\n%s\n\n%s\n\n%s\n\n---\n", string(submatches[1]), string(submatches[2]), string(submatches[3])) + // Trim any space or port number that might be on the host + split := strings.Split(strings.TrimSpace(string(submatches[3])), ":") + hostname = split[0] + } + } //log.Printf("getHostnameFromSNI: %s\n", hostname) @@ -282,9 +295,10 @@ func (vaddr *vaddrStorage) getListenerInfo(conn net.Conn) (*ListenerInfo, string if globToUse == "" { globToUse = "*" } - numberOfPeriods := len(regexp.MustCompile(`\.`).FindAllString(globToUse, -1)) - numberOfGlobs := len(regexp.MustCompile(`\*+`).FindAllString(globToUse, -1)) + numberOfPeriods := len(vaddr.dotRegex.FindAllString(globToUse, -1)) + numberOfGlobs := len(vaddr.globRegex.FindAllString(globToUse, -1)) specificity := numberOfPeriods - numberOfGlobs + //log.Printf("%d > %d && Glob(%s, %s) (%t)\n", specificity, recordSpecificity, globToUse, hostname, Glob(globToUse, hostname)) if specificity > recordSpecificity && Glob(globToUse, hostname) { recordSpecificity = specificity mostSpecificMatchingBackend = &backend From ca4bdab72551e1a4fb6f99d526145f3ea97fd634 Mon Sep 17 00:00:00 2001 From: forest Date: Mon, 29 Mar 2021 15:20:31 -0500 Subject: [PATCH 11/36] got metric collection working with greenhouse --- main_server.go | 255 ++++++++++++++++++++++++++++++------------------- 1 file changed, 155 insertions(+), 100 deletions(-) diff --git a/main_server.go b/main_server.go index d443ea5..e76a81e 100644 --- a/main_server.go +++ b/main_server.go @@ -16,7 +16,6 @@ import ( "regexp" "strings" "sync" - "time" tunnel "git.sequentialread.com/forest/threshold/tunnel-lib" ) @@ -68,7 +67,10 @@ type BandwidthCounter struct { Outbound int64 } -type MultiTenantInternalAPI struct{} +type MultiTenantInternalAPI struct { + InboundByTenant map[string]int64 + OutboundByTenant map[string]int64 +} type PrometheusMetricsAPI struct { MultiTenantServerMode bool @@ -114,7 +116,6 @@ func runServer(configFileName *string) { // the Server should only collect metrics when in multi-tenant mode -- this is needed for billing if config.MultiTenantMode { metricChannel = make(chan tunnel.BandwidthMetric) - go exportMetrics(config.Metrics /*multiTenantServerMode: */, true, metricChannel) } tunnelServerConfig := &tunnel.ServerConfig{ @@ -215,12 +216,31 @@ func runServer(configFileName *string) { } tlsConfig.BuildNameToCertificate() + internalHandler := &MultiTenantInternalAPI{ + InboundByTenant: map[string]int64{}, + OutboundByTenant: map[string]int64{}, + } multiTenantInternalServer := &http.Server{ Addr: fmt.Sprintf(":%d", config.MultiTenantInternalAPIListenPort), TLSConfig: tlsConfig, - Handler: &MultiTenantInternalAPI{}, + Handler: internalHandler, } + go (func() { + for { + metric := <-metricChannel + tenantIdNodeId := strings.Split(metric.ClientId, ".") + if len(tenantIdNodeId) != 2 { + panic(fmt.Errorf("malformed metric.ClientId '%s', expected .", metric.ClientId)) + } + if metric.Inbound { + internalHandler.InboundByTenant[tenantIdNodeId[0]] += int64(metric.Bytes) + } else { + internalHandler.OutboundByTenant[tenantIdNodeId[0]] += int64(metric.Bytes) + } + } + })() + err = multiTenantInternalServer.ListenAndServeTLS(config.ServerTlsCertificateFile, config.ServerTlsKeyFile) panic(err) })() @@ -353,102 +373,103 @@ func setListeners(tenantId string, listenerConfigs []ListenerConfig) (int, strin } -func exportMetrics(config MetricsConfig, multiTenantServerMode bool, bandwidth <-chan tunnel.BandwidthMetric) { - metricsAPI := &PrometheusMetricsAPI{ - MultiTenantServerMode: multiTenantServerMode, - InboundByTenant: map[string]int64{}, - OutboundByTenant: map[string]int64{}, - InboundByService: map[string]int64{}, - OutboundByService: map[string]int64{}, - } - - go (func() { - for { - metric := <-bandwidth - if multiTenantServerMode { - tenantIdNodeId := strings.Split(metric.ClientId, ".") - if len(tenantIdNodeId) != 2 { - panic(fmt.Errorf("malformed metric.ClientId '%s', expected .", metric.ClientId)) - } - if metric.Inbound { - metricsAPI.InboundByTenant[tenantIdNodeId[0]] += int64(metric.Bytes) - } else { - metricsAPI.OutboundByTenant[tenantIdNodeId[0]] += int64(metric.Bytes) - } - } else { - // TODO shouldn't this be done on the client side only ?? - if metric.Inbound { - metricsAPI.InboundByService[metric.Service] += int64(metric.Bytes) - } else { - metricsAPI.OutboundByService[metric.Service] += int64(metric.Bytes) - } - } - } - })() - - go (func() { - metricsServer := &http.Server{ - Addr: fmt.Sprintf(":%d", config.PrometheusMetricsAPIPort), - Handler: metricsAPI, - } - err := metricsServer.ListenAndServe() - panic(err) - })() -} - -// TODO move this to the management API / to the client side. -func (s *PrometheusMetricsAPI) ServeHTTP(responseWriter http.ResponseWriter, request *http.Request) { - - getMillisecondsSinceUnixEpoch := func() int64 { - return time.Now().UnixNano() / int64(time.Millisecond) - } - - writeMetric := func(inbound map[string]int64, outbound map[string]int64, name, tag, desc string) { - timestamp := getMillisecondsSinceUnixEpoch() - responseWriter.Write([]byte(fmt.Sprintf("# HELP %s %s\n", name, desc))) - responseWriter.Write([]byte(fmt.Sprintf("# TYPE %s counter\n", name))) - for id, bytez := range inbound { - responseWriter.Write([]byte(fmt.Sprintf("%s{%s=\"%s\",direction=\"inbound\"} %d %d\n", name, tag, id, bytez, timestamp))) - } - for id, bytez := range outbound { - responseWriter.Write([]byte(fmt.Sprintf("%s{%s=\"%s\",direction=\"outbound\"} %d %d\n", name, tag, id, bytez, timestamp))) - } - } - - if strings.Contains(request.Header.Get("Accept"), "application/json") && !strings.Contains(request.Header.Get("Accept"), "text/plain") { - var bytez []byte - var err error - if s.MultiTenantServerMode { - bytez, err = json.MarshalIndent(PrometheusMetricsAPI{ - InboundByTenant: s.InboundByTenant, - OutboundByTenant: s.OutboundByTenant, - }, "", " ") - } else { - // TODO this should probably only be supported on the client side - bytez, err = json.MarshalIndent(PrometheusMetricsAPI{ - InboundByService: s.InboundByService, - OutboundByService: s.OutboundByService, - }, "", " ") - } - - if err != nil { - log.Printf(fmt.Sprintf("500 internal server error: %s", err)) - http.Error(responseWriter, "500 internal server error", http.StatusInternalServerError) - return - } - - responseWriter.Header().Set("Content-Type", "application/json") - responseWriter.Write(bytez) - } else { - responseWriter.Header().Set("Content-Type", "text/plain; version=0.0.4") - - if s.MultiTenantServerMode { - writeMetric(s.InboundByTenant, s.OutboundByTenant, "bandwidth_by_tenant", "tenant", "bandwidth usage by tenant in bytes, excluding usage from control protocol.") - } else { - writeMetric(s.InboundByService, s.OutboundByService, "bandwidth_by_service", "service", "bandwidth usage by service in bytes.") - } - } -} +// TODO move the prometheus metrics to the client +// func exportMetrics(config MetricsConfig, multiTenantServerMode bool, bandwidth <-chan tunnel.BandwidthMetric) { +// metricsAPI := &PrometheusMetricsAPI{ +// MultiTenantServerMode: multiTenantServerMode, +// InboundByTenant: map[string]int64{}, +// OutboundByTenant: map[string]int64{}, +// InboundByService: map[string]int64{}, +// OutboundByService: map[string]int64{}, +// } + +// go (func() { +// for { +// metric := <-bandwidth +// if multiTenantServerMode { +// tenantIdNodeId := strings.Split(metric.ClientId, ".") +// if len(tenantIdNodeId) != 2 { +// panic(fmt.Errorf("malformed metric.ClientId '%s', expected .", metric.ClientId)) +// } +// if metric.Inbound { +// metricsAPI.InboundByTenant[tenantIdNodeId[0]] += int64(metric.Bytes) +// } else { +// metricsAPI.OutboundByTenant[tenantIdNodeId[0]] += int64(metric.Bytes) +// } +// } else { +// // TODO shouldn't this be done on the client side only ?? +// if metric.Inbound { +// metricsAPI.InboundByService[metric.Service] += int64(metric.Bytes) +// } else { +// metricsAPI.OutboundByService[metric.Service] += int64(metric.Bytes) +// } +// } +// } +// })() + +// go (func() { +// metricsServer := &http.Server{ +// Addr: fmt.Sprintf(":%d", config.PrometheusMetricsAPIPort), +// Handler: metricsAPI, +// } +// err := metricsServer.ListenAndServe() +// panic(err) +// })() +// } + +// // TODO move this to the management API / to the client side. +// func (s *PrometheusMetricsAPI) ServeHTTP(responseWriter http.ResponseWriter, request *http.Request) { + +// getMillisecondsSinceUnixEpoch := func() int64 { +// return time.Now().UnixNano() / int64(time.Millisecond) +// } + +// writeMetric := func(inbound map[string]int64, outbound map[string]int64, name, tag, desc string) { +// timestamp := getMillisecondsSinceUnixEpoch() +// responseWriter.Write([]byte(fmt.Sprintf("# HELP %s %s\n", name, desc))) +// responseWriter.Write([]byte(fmt.Sprintf("# TYPE %s counter\n", name))) +// for id, bytez := range inbound { +// responseWriter.Write([]byte(fmt.Sprintf("%s{%s=\"%s\",direction=\"inbound\"} %d %d\n", name, tag, id, bytez, timestamp))) +// } +// for id, bytez := range outbound { +// responseWriter.Write([]byte(fmt.Sprintf("%s{%s=\"%s\",direction=\"outbound\"} %d %d\n", name, tag, id, bytez, timestamp))) +// } +// } + +// if strings.Contains(request.Header.Get("Accept"), "application/json") && !strings.Contains(request.Header.Get("Accept"), "text/plain") { +// var bytez []byte +// var err error +// if s.MultiTenantServerMode { +// bytez, err = json.MarshalIndent(PrometheusMetricsAPI{ +// InboundByTenant: s.InboundByTenant, +// OutboundByTenant: s.OutboundByTenant, +// }, "", " ") +// } else { +// // TODO this should probably only be supported on the client side +// bytez, err = json.MarshalIndent(PrometheusMetricsAPI{ +// InboundByService: s.InboundByService, +// OutboundByService: s.OutboundByService, +// }, "", " ") +// } + +// if err != nil { +// log.Printf(fmt.Sprintf("500 internal server error: %s", err)) +// http.Error(responseWriter, "500 internal server error", http.StatusInternalServerError) +// return +// } + +// responseWriter.Header().Set("Content-Type", "application/json") +// responseWriter.Write(bytez) +// } else { +// responseWriter.Header().Set("Content-Type", "text/plain; version=0.0.4") + +// if s.MultiTenantServerMode { +// writeMetric(s.InboundByTenant, s.OutboundByTenant, "bandwidth_by_tenant", "tenant", "bandwidth usage by tenant in bytes, excluding usage from control protocol.") +// } else { +// writeMetric(s.InboundByService, s.OutboundByService, "bandwidth_by_service", "service", "bandwidth usage by service in bytes.") +// } +// } +// } func compareListenerConfigs(a, b ListenerConfig) bool { return (a.ListenPort == b.ListenPort && @@ -500,6 +521,40 @@ func (s *MultiTenantInternalAPI) ServeHTTP(responseWriter http.ResponseWriter, r responseWriter.Header().Add("Allow", "GET") http.Error(responseWriter, "405 Method Not Allowed, try GET or PUT", http.StatusMethodNotAllowed) } + case "/consumeMetrics": + if request.Method == "GET" { + bytez, err := json.Marshal(struct { + InboundByTenant map[string]int64 + OutboundByTenant map[string]int64 + }{ + InboundByTenant: s.InboundByTenant, + OutboundByTenant: s.OutboundByTenant, + }) + if err != nil { + http.Error(responseWriter, "500 JSON Marshal Error", http.StatusInternalServerError) + return + } + inboundToDelete := []string{} + outboundToDelete := []string{} + for k := range s.InboundByTenant { + inboundToDelete = append(inboundToDelete, k) + } + for k := range s.OutboundByTenant { + outboundToDelete = append(outboundToDelete, k) + } + for _, k := range inboundToDelete { + delete(s.InboundByTenant, k) + } + for _, k := range outboundToDelete { + delete(s.OutboundByTenant, k) + } + + responseWriter.Header().Set("Content-Type", "application/json") + responseWriter.Write(bytez) + } else { + responseWriter.Header().Set("Allow", "GET") + http.Error(responseWriter, "405 method not allowed, try GET", http.StatusMethodNotAllowed) + } case "/ping": if request.Method == "GET" { fmt.Fprint(responseWriter, "pong") From 6cb229dd0c90d818dae9fc0ec4ca2cdc23fa3826 Mon Sep 17 00:00:00 2001 From: forest Date: Sat, 3 Apr 2021 14:53:26 -0500 Subject: [PATCH 12/36] allow inline certs in config file --- main_client.go | 59 +++++++++++++++++++++++++++++++++++++++----------- main_server.go | 9 ++++++++ 2 files changed, 55 insertions(+), 13 deletions(-) diff --git a/main_client.go b/main_client.go index 0f83d51..3e2c314 100644 --- a/main_client.go +++ b/main_client.go @@ -33,6 +33,9 @@ type ClientConfig struct { CaCertificateFilesGlob string ClientTlsKeyFile string ClientTlsCertificateFile string + CaCertificate string + ClientTlsKey string + ClientTlsCertificate string AdminUnixSocket string Metrics MetricsConfig } @@ -144,7 +147,11 @@ func runClient(configFileName *string) { clientServers = []ClientServer{makeServer(config.ServerAddr)} } - serviceToLocalAddrMap = config.ServiceToLocalAddrMap + if config.ServiceToLocalAddrMap != nil { + serviceToLocalAddrMap = config.ServiceToLocalAddrMap + } else { + serviceToLocalAddrMap = &(map[string]string{}) + } configToLog, _ := json.MarshalIndent(config, "", " ") configToLogString := string(configToLog) @@ -160,9 +167,21 @@ func runClient(configFileName *string) { dialFunction := net.Dial - cert, err := tls.LoadX509KeyPair(config.ClientTlsCertificateFile, config.ClientTlsKeyFile) - if err != nil { - log.Fatal(err) + var cert tls.Certificate + hasFiles := config.ClientTlsCertificateFile != "" && config.ClientTlsKeyFile != "" + hasLiterals := config.ClientTlsCertificate != "" && config.ClientTlsKey != "" + if hasFiles && !hasLiterals { + cert, err = tls.LoadX509KeyPair(config.ClientTlsCertificateFile, config.ClientTlsKeyFile) + if err != nil { + log.Fatal(err) + } + } else if !hasFiles && hasLiterals { + cert, err = tls.X509KeyPair([]byte(config.ClientTlsCertificate), []byte(config.ClientTlsKeyFile)) + if err != nil { + log.Fatal(err) + } + } else { + log.Fatal("one or the other (not both) of ClientTlsCertificateFile+ClientTlsKeyFile or ClientTlsCertificate+ClientTlsKey is required\n") } parsedCert, err := x509.ParseCertificate(cert.Certificate[0]) @@ -198,18 +217,30 @@ func runClient(configFileName *string) { )) } - certificates, err := filepath.Glob(config.CaCertificateFilesGlob) - if err != nil { - log.Fatal(err) - } - caCertPool := x509.NewCertPool() - for _, filename := range certificates { - caCert, err := ioutil.ReadFile(filename) + if config.CaCertificateFilesGlob != "" && config.CaCertificate == "" { + certificates, err := filepath.Glob(config.CaCertificateFilesGlob) if err != nil { log.Fatal(err) } - caCertPool.AppendCertsFromPEM(caCert) + + for _, filename := range certificates { + caCert, err := ioutil.ReadFile(filename) + if err != nil { + log.Fatal(err) + } + ok := caCertPool.AppendCertsFromPEM(caCert) + if !ok { + log.Fatalf("Failed to add CA certificate '%s' to cert pool\n", filename) + } + } + } else if config.CaCertificateFilesGlob == "" && config.CaCertificate != "" { + ok := caCertPool.AppendCertsFromPEM([]byte(config.CaCertificate)) + if !ok { + log.Fatal("Failed to add config.CaCertificate to cert pool\n") + } + } else { + log.Fatal("one or the other (not both) of CaCertificateFilesGlob or CaCertificate is required\n") } tlsClientConfig = &tls.Config{ @@ -364,7 +395,9 @@ func (handler clientAdminAPI) ServeHTTP(response http.ResponseWriter, request *h } } - serviceToLocalAddrMap = &configUpdate.ServiceToLocalAddrMap + if &configUpdate.ServiceToLocalAddrMap != nil { + serviceToLocalAddrMap = &configUpdate.ServiceToLocalAddrMap + } response.Header().Add("content-type", "application/json") response.WriteHeader(http.StatusOK) diff --git a/main_server.go b/main_server.go index e76a81e..1377a2d 100644 --- a/main_server.go +++ b/main_server.go @@ -549,6 +549,15 @@ func (s *MultiTenantInternalAPI) ServeHTTP(responseWriter http.ResponseWriter, r delete(s.OutboundByTenant, k) } + // bytez2, err := json.Marshal(struct { + // InboundByTenant map[string]int64 + // OutboundByTenant map[string]int64 + // }{ + // InboundByTenant: s.InboundByTenant, + // OutboundByTenant: s.OutboundByTenant, + // }) + //log.Printf("returnedBytes: %s\n\ncurrentBytes: %s\n\n", string(bytez), string(bytez2)) + responseWriter.Header().Set("Content-Type", "application/json") responseWriter.Write(bytez) } else { From d0f009120adca021e7f180b4ca0ad521728a1252 Mon Sep 17 00:00:00 2001 From: forest Date: Tue, 6 Apr 2021 20:52:42 -0500 Subject: [PATCH 13/36] add clientStates endpoint for greenhouse to be able to tell if a given nodeId is taken yet or not --- main_server.go | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/main_server.go b/main_server.go index 1377a2d..c468f11 100644 --- a/main_server.go +++ b/main_server.go @@ -482,6 +482,20 @@ func compareListenerConfigs(a, b ListenerConfig) bool { func (s *MultiTenantInternalAPI) ServeHTTP(responseWriter http.ResponseWriter, request *http.Request) { switch path.Clean(request.URL.Path) { + case "/clientStates": + tenantId := request.URL.Query().Get("tenantId") + if _, hasClientStatesByTenant := clientStatesByTenant[tenantId]; tenantId == "" || !hasClientStatesByTenant { + responseWriter.Header().Set("Content-Type", "application/json") + responseWriter.Write([]byte("{}")) + } else { + bytes, err := json.Marshal(clientStatesByTenant[tenantId]) + if err != nil { + http.Error(responseWriter, "500 JSON Marshal Error", http.StatusInternalServerError) + return + } + responseWriter.Header().Set("Content-Type", "application/json") + responseWriter.Write(bytes) + } case "/tenants": if request.Method == "GET" || request.Method == "PUT" { if request.Method == "PUT" { From cbcbed9bb15c9935c7779b19c37acf31a08abddc Mon Sep 17 00:00:00 2001 From: forest Date: Wed, 7 Apr 2021 17:18:31 -0500 Subject: [PATCH 14/36] debugging desktop app registration stuff --- build.sh | 4 +- main_client.go | 111 +++++++++++++++++++++++++++++++++++-------------- 2 files changed, 81 insertions(+), 34 deletions(-) diff --git a/build.sh b/build.sh index fb1baf9..b06a5c4 100755 --- a/build.sh +++ b/build.sh @@ -44,6 +44,6 @@ function build() { } -build arm +#build arm build amd64 -build arm64 \ No newline at end of file +#build arm64 \ No newline at end of file diff --git a/main_client.go b/main_client.go index 3e2c314..1536d1e 100644 --- a/main_client.go +++ b/main_client.go @@ -22,22 +22,26 @@ import ( ) type ClientConfig struct { - DebugLog bool - ClientId string - GreenhouseDomain string - GreenhouseAPIKey string - GreenhouseThresholdPort int - ServerAddr string - Servers []string - ServiceToLocalAddrMap *map[string]string - CaCertificateFilesGlob string - ClientTlsKeyFile string - ClientTlsCertificateFile string - CaCertificate string - ClientTlsKey string - ClientTlsCertificate string - AdminUnixSocket string - Metrics MetricsConfig + DebugLog bool + ClientId string + GreenhouseDomain string + GreenhouseAPIKey string + GreenhouseThresholdPort int + ServerAddr string + Servers []string + ServiceToLocalAddrMap *map[string]string + CaCertificateFilesGlob string + ClientTlsKeyFile string + ClientTlsCertificateFile string + CaCertificate string + ClientTlsKey string + ClientTlsCertificate string + AdminUnixSocket string + AdminAPIPort int + AdminAPICACertificateFile string + AdminAPITlsKeyFile string + AdminAPITlsCertificateFile string + Metrics MetricsConfig } type ClientServer struct { @@ -173,12 +177,13 @@ func runClient(configFileName *string) { if hasFiles && !hasLiterals { cert, err = tls.LoadX509KeyPair(config.ClientTlsCertificateFile, config.ClientTlsKeyFile) if err != nil { - log.Fatal(err) + log.Fatal(fmt.Sprintf("can't start because tls.LoadX509KeyPair returned: \n%+v\n", err)) } } else if !hasFiles && hasLiterals { - cert, err = tls.X509KeyPair([]byte(config.ClientTlsCertificate), []byte(config.ClientTlsKeyFile)) + + cert, err = tls.X509KeyPair([]byte(config.ClientTlsCertificate), []byte(config.ClientTlsKey)) if err != nil { - log.Fatal(err) + log.Fatal(fmt.Sprintf("can't start because tls.X509KeyPair returned: \n%+v\n", err)) } } else { log.Fatal("one or the other (not both) of ClientTlsCertificateFile+ClientTlsKeyFile or ClientTlsCertificate+ClientTlsKey is required\n") @@ -259,7 +264,7 @@ func runClient(configFileName *string) { //log.Printf("(*serviceToLocalAddrMap): %+v\n\n", (*serviceToLocalAddrMap)) localAddr, hasLocalAddr := (*serviceToLocalAddrMap)[service] if !hasLocalAddr { - return "", fmt.Errorf("service '%s' not configured. Set ServiceToLocalAddrMap in client config file or HTTP PUT /liveconfig over the AdminUnixSocket.", service) + return "", fmt.Errorf("service '%s' not configured. Set ServiceToLocalAddrMap in client config file or HTTP PUT /liveconfig over the admin api.", service) } return localAddr, nil } @@ -299,19 +304,61 @@ func runClient(configFileName *string) { func runClientAdminApi(config ClientConfig) { - os.Remove(config.AdminUnixSocket) + var listener net.Listener + if config.AdminUnixSocket != "" && config.AdminAPIPort == 0 { + os.Remove(config.AdminUnixSocket) - listenAddress, err := net.ResolveUnixAddr("unix", config.AdminUnixSocket) - if err != nil { - panic(fmt.Sprintf("runClient(): can't start because net.ResolveUnixAddr() returned %+v", err)) - } + listenAddress, err := net.ResolveUnixAddr("unix", config.AdminUnixSocket) + if err != nil { + panic(fmt.Sprintf("runClient(): can't start because net.ResolveUnixAddr() returned %+v", err)) + } - listener, err := net.ListenUnix("unix", listenAddress) - if err != nil { - panic(fmt.Sprintf("can't start because net.ListenUnix() returned %+v", err)) + listener, err = net.ListenUnix("unix", listenAddress) + if err != nil { + panic(fmt.Sprintf("can't start because net.ListenUnix() returned %+v", err)) + } + log.Printf("AdminUnixSocket Listening: %v\n\n", config.AdminUnixSocket) + defer listener.Close() + } else if config.AdminUnixSocket == "" && config.AdminAPIPort != 0 { + addrString := fmt.Sprintf("127.0.0.1:%d", config.AdminAPIPort) + addr, err := net.ResolveTCPAddr("tcp", addrString) + if err != nil { + panic(fmt.Sprintf("runClient(): can't start because net.ResolveTCPAddr(%s) returned %+v", addrString, err)) + } + tcpListener, err := net.ListenTCP("tcp", addr) + if err != nil { + panic(fmt.Sprintf("runClient(): can't start because net.ListenTCP(%s) returned %+v", addrString, err)) + } + + caCertPool := x509.NewCertPool() + caCertBytes, err := ioutil.ReadFile(config.AdminAPICACertificateFile) + if err != nil { + panic(fmt.Sprintf("runClient(): can't start because ioutil.ReadFile(%s) returned %+v", config.AdminAPICACertificateFile, err)) + } + caCertPool.AppendCertsFromPEM(caCertBytes) + + tlsCert, err := tls.LoadX509KeyPair(config.AdminAPITlsCertificateFile, config.AdminAPITlsKeyFile) + if err != nil { + panic(fmt.Sprintf( + "runClient(): can't start because tls.LoadX509KeyPair(%s,%s) returned %+v", + config.AdminAPITlsCertificateFile, config.AdminAPITlsKeyFile, err, + )) + } + + tlsConfig := &tls.Config{ + Certificates: []tls.Certificate{tlsCert}, + ClientCAs: caCertPool, + ClientAuth: tls.RequireAndVerifyClientCert, + } + tlsConfig.BuildNameToCertificate() + + listener = tls.NewListener(tcpListener, tlsConfig) + } else if config.AdminUnixSocket != "" && config.AdminAPIPort != 0 { + log.Fatal("One or the other (and not both) of AdminUnixSocket or AdminAPIPort is required") + return + } else if config.AdminUnixSocket == "" && config.AdminAPIPort == 0 { + return } - log.Printf("AdminUnixSocket Listening: %v\n\n", config.AdminUnixSocket) - defer listener.Close() server := http.Server{ Handler: clientAdminAPI{}, @@ -319,9 +366,9 @@ func runClientAdminApi(config ClientConfig) { WriteTimeout: 10 * time.Second, } - err = server.Serve(listener) + err := server.Serve(listener) if err != nil { - panic(fmt.Sprintf("AdminUnixSocket server returned %+v", err)) + panic(fmt.Sprintf("Admin API server returned %+v", err)) } } From e2d165e1cb5733f1af717ed75aae268d7afa33f5 Mon Sep 17 00:00:00 2001 From: forest Date: Wed, 7 Apr 2021 17:47:39 -0500 Subject: [PATCH 15/36] =?UTF-8?q?move=20blocking=20IO=20reads=20outside=20?= =?UTF-8?q?of=20mutex=20=F0=9F=98=85?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tunnel-lib/server.go | 10 +++++++ tunnel-lib/virtualaddr.go | 55 ++++++++++++++++++--------------------- 2 files changed, 36 insertions(+), 29 deletions(-) diff --git a/tunnel-lib/server.go b/tunnel-lib/server.go index f3b0cd2..fac4dfb 100644 --- a/tunnel-lib/server.go +++ b/tunnel-lib/server.go @@ -188,11 +188,13 @@ func (s *Server) ServeHTTP(responseWriter http.ResponseWriter, request *http.Req func (s *Server) serveTCP() { for conn := range s.connCh { + log.Println(3) go s.serveTCPConn(conn) } } func (s *Server) serveTCPConn(conn net.Conn) { + log.Println(4) err := s.handleTCPConn(conn) if err != nil { log.Printf("Server.serveTCPConn(): failed to serve %q: %s\n", conn.RemoteAddr(), err) @@ -203,7 +205,10 @@ func (s *Server) serveTCPConn(conn net.Conn) { func (s *Server) handleTCPConn(conn net.Conn) error { // TODO getListenerInfo should return the bytes we read to try to get teh hostname // then we stream.write those right after the SendProxyProtocolv1 bit. + + log.Println(5) listenerInfo, sniHostname, connectionHeader := s.virtualAddrs.getListenerInfo(conn) + log.Println(6) if listenerInfo == nil { return fmt.Errorf("no virtual host available for %s (hostname: %s)", conn.LocalAddr(), sniHostname) } @@ -217,7 +222,9 @@ func (s *Server) handleTCPConn(conn net.Conn) error { if listenerInfo.BackendService != "" { service = listenerInfo.BackendService } + log.Println(7) stream, err := s.dial(listenerInfo.AssociatedClientId, service) + log.Println(8) if err != nil { return err } @@ -239,9 +246,11 @@ func (s *Server) handleTCPConn(conn net.Conn) error { stream.Write([]byte(fmt.Sprintf("PROXY %s %s %s %s %s\r\n", proxyNetwork, remoteHost, localHost, remotePort, localPort))) } + log.Println(9) if len(connectionHeader) > 0 { stream.Write(connectionHeader) } + log.Println(10) disconnectedChan := make(chan bool) @@ -263,6 +272,7 @@ func (s *Server) handleTCPConn(conn net.Conn) error { // Once one member of this conversation has disconnected, we should end the conversation for all parties. <-disconnectedChan + log.Println(11) return nonil(stream.Close(), conn.Close()) } diff --git a/tunnel-lib/virtualaddr.go b/tunnel-lib/virtualaddr.go index 2b02b7c..ea4200a 100644 --- a/tunnel-lib/virtualaddr.go +++ b/tunnel-lib/virtualaddr.go @@ -72,13 +72,13 @@ func (l *listener) serve() { log.Printf("listener.serve(): failue listening on %q: %s\n", l.Addr(), err) return } - + log.Println(1) if atomic.LoadInt32(&l.done) != 0 { log.Printf("listener.serve(): stopped serving %q", l.Addr()) conn.Close() return } - + log.Println(2) l.connCh <- conn } } @@ -238,8 +238,27 @@ func (vaddr *vaddrStorage) HasIdentifier(identifier string) bool { } func (vaddr *vaddrStorage) getListenerInfo(conn net.Conn) (*ListenerInfo, string, []byte) { - vaddr.mu.Lock() - defer vaddr.mu.Unlock() + connectionHeader := make([]byte, 4096) + n, err := conn.Read(connectionHeader) + if err != nil && err != io.EOF { + log.Printf("vaddrStorage.getListenerInfo(): failed to read header for connection %q: %s", conn.LocalAddr(), err) + return nil, "", make([]byte, 0) + } + + hostname, err := getHostnameFromSNI(connectionHeader[:n]) + + if err != nil { + // If we failed to get the hostname from SNI, try to get it from HTTP/1.1 + + submatches := vaddr.httpHostRegex.FindSubmatch(connectionHeader[:n]) + //log.Printf("--\n%d\n--\n", len(submatches)) + if submatches != nil && len(submatches) == 4 { + //log.Printf("---\n\n%s\n\n%s\n\n%s\n\n---\n", string(submatches[1]), string(submatches[2]), string(submatches[3])) + // Trim any space or port number that might be on the host + split := strings.Split(strings.TrimSpace(string(submatches[3])), ":") + hostname = split[0] + } + } host, port, err := parseHostPort(conn.LocalAddr().String()) if err != nil { @@ -247,6 +266,9 @@ func (vaddr *vaddrStorage) getListenerInfo(conn net.Conn) (*ListenerInfo, string return nil, "", make([]byte, 0) } + vaddr.mu.Lock() + defer vaddr.mu.Unlock() + for _, listener := range vaddr.listeners { listenerHost, listenerPort, err := parseHostPort(listener.localAddr()) if err != nil { @@ -263,31 +285,6 @@ func (vaddr *vaddrStorage) getListenerInfo(conn net.Conn) (*ListenerInfo, string if err == nil && listenHostMatches && listenPortMatches { - //log.Printf("pre getHostnameFromSNI ") - - connectionHeader := make([]byte, 4096) - n, err := conn.Read(connectionHeader) - if err != nil && err != io.EOF { - log.Printf("vaddrStorage.getListenerInfo(): failed to read header for connection %q: %s", conn.LocalAddr(), err) - return nil, "", make([]byte, 0) - } - - hostname, err := getHostnameFromSNI(connectionHeader[:n]) - - // This will happen every time someone connects with a non-TLS protocol. - if err != nil { - submatches := vaddr.httpHostRegex.FindSubmatch(connectionHeader[:n]) - //log.Printf("--\n%d\n--\n", len(submatches)) - if submatches != nil && len(submatches) == 4 { - //log.Printf("---\n\n%s\n\n%s\n\n%s\n\n---\n", string(submatches[1]), string(submatches[2]), string(submatches[3])) - // Trim any space or port number that might be on the host - split := strings.Split(strings.TrimSpace(string(submatches[3])), ":") - hostname = split[0] - } - } - - //log.Printf("getHostnameFromSNI: %s\n", hostname) - recordSpecificity := -10 var mostSpecificMatchingBackend *ListenerInfo = nil for _, backend := range listener.backends { From ae543f018a33649492aaf57d66e691ccca7540f1 Mon Sep 17 00:00:00 2001 From: forest Date: Mon, 12 Apr 2021 09:49:03 -0500 Subject: [PATCH 16/36] greenhouseapikey --> greenhouseapitoken --- main_client.go | 14 +++++++------- tunnel-lib/virtualaddr.go | 2 ++ 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/main_client.go b/main_client.go index 1536d1e..4a25469 100644 --- a/main_client.go +++ b/main_client.go @@ -25,7 +25,7 @@ type ClientConfig struct { DebugLog bool ClientId string GreenhouseDomain string - GreenhouseAPIKey string + GreenhouseAPIToken string GreenhouseThresholdPort int ServerAddr string Servers []string @@ -96,8 +96,8 @@ func runClient(configFileName *string) { if config.Servers != nil && len(config.Servers) > 0 { log.Fatal("config contains both GreenhouseDomain and Servers, only use one or the other") } - if config.GreenhouseAPIKey == "" { - log.Fatal("config contains GreenhouseDomain but does not contain GreenhouseAPIKey, use both or niether") + if config.GreenhouseAPIToken == "" { + log.Fatal("config contains GreenhouseDomain but does not contain GreenhouseAPIToken, use both or niether") } greenhouseClient := http.Client{Timeout: time.Second * 10} @@ -106,13 +106,13 @@ func runClient(configFileName *string) { if err != nil { log.Fatal("invalid GreenhouseDomain '%s', can't create http request for %s", config.GreenhouseDomain, greenhouseURL) } - request.Header.Add("Authorization", fmt.Sprintf("Bearer %s", config.GreenhouseAPIKey)) + request.Header.Add("Authorization", fmt.Sprintf("Bearer %s", config.GreenhouseAPIToken)) response, err := greenhouseClient.Do(request) if err != nil || response.StatusCode != 200 { if err == nil { if response.StatusCode == 401 { - log.Fatalf("bad or expired GreenhouseAPIKey, recieved HTTP 401 Unauthorized from Greenhouse server %s", greenhouseURL) + log.Fatalf("bad or expired GreenhouseAPIToken, recieved HTTP 401 Unauthorized from Greenhouse server %s", greenhouseURL) } else { log.Fatalf("server error: recieved HTTP %d from Greenhouse server %s", response.StatusCode, greenhouseURL) } @@ -161,7 +161,7 @@ func runClient(configFileName *string) { configToLogString := string(configToLog) configToLogString = regexp.MustCompile( - `("GreenhouseAPIKey": ")[^"]+(",)`, + `("GreenhouseAPIToken": ")[^"]+(",)`, ).ReplaceAllString( configToLogString, "$1******$2", @@ -180,11 +180,11 @@ func runClient(configFileName *string) { log.Fatal(fmt.Sprintf("can't start because tls.LoadX509KeyPair returned: \n%+v\n", err)) } } else if !hasFiles && hasLiterals { - cert, err = tls.X509KeyPair([]byte(config.ClientTlsCertificate), []byte(config.ClientTlsKey)) if err != nil { log.Fatal(fmt.Sprintf("can't start because tls.X509KeyPair returned: \n%+v\n", err)) } + } else { log.Fatal("one or the other (not both) of ClientTlsCertificateFile+ClientTlsKeyFile or ClientTlsCertificate+ClientTlsKey is required\n") } diff --git a/tunnel-lib/virtualaddr.go b/tunnel-lib/virtualaddr.go index ea4200a..02f140c 100644 --- a/tunnel-lib/virtualaddr.go +++ b/tunnel-lib/virtualaddr.go @@ -238,6 +238,8 @@ func (vaddr *vaddrStorage) HasIdentifier(identifier string) bool { } func (vaddr *vaddrStorage) getListenerInfo(conn net.Conn) (*ListenerInfo, string, []byte) { + + // TODO maybe want to figure out how to set the read timeout lower for this ?? connectionHeader := make([]byte, 4096) n, err := conn.Read(connectionHeader) if err != nil && err != io.EOF { From 80a61c02953c9ae519b9db09e239903b123e3f30 Mon Sep 17 00:00:00 2001 From: forest Date: Tue, 27 Apr 2021 16:08:39 -0500 Subject: [PATCH 17/36] add tenantInfo endpoint for greenhouse --- main_server.go | 39 +++++++++++++++++++++++++++------------ 1 file changed, 27 insertions(+), 12 deletions(-) diff --git a/main_server.go b/main_server.go index c468f11..e446353 100644 --- a/main_server.go +++ b/main_server.go @@ -482,20 +482,35 @@ func compareListenerConfigs(a, b ListenerConfig) bool { func (s *MultiTenantInternalAPI) ServeHTTP(responseWriter http.ResponseWriter, request *http.Request) { switch path.Clean(request.URL.Path) { - case "/clientStates": + case "/tenantInfo": tenantId := request.URL.Query().Get("tenantId") - if _, hasClientStatesByTenant := clientStatesByTenant[tenantId]; tenantId == "" || !hasClientStatesByTenant { - responseWriter.Header().Set("Content-Type", "application/json") - responseWriter.Write([]byte("{}")) - } else { - bytes, err := json.Marshal(clientStatesByTenant[tenantId]) - if err != nil { - http.Error(responseWriter, "500 JSON Marshal Error", http.StatusInternalServerError) - return - } - responseWriter.Header().Set("Content-Type", "application/json") - responseWriter.Write(bytes) + clientStates, hasClientStatesByTenant := clientStatesByTenant[tenantId] + listeners, hasListenersByTenant := listenersByTenant[tenantId] + + if tenantId == "" || tenantId == "0" { + http.Error(responseWriter, "400 Bad Request: tenantId url parameter is required", http.StatusBadRequest) + } + + if !hasClientStatesByTenant { + clientStates = map[string]ClientState{} + } + if !hasListenersByTenant { + listeners = []ListenerConfig{} + } + resultObject := struct { + ClientStates map[string]ClientState + Listeners []ListenerConfig + }{ + ClientStates: clientStates, + Listeners: listeners, + } + bytes, err := json.Marshal(resultObject) + if err != nil { + http.Error(responseWriter, "500 JSON Marshal Error", http.StatusInternalServerError) + return } + responseWriter.Header().Set("Content-Type", "application/json") + responseWriter.Write(bytes) case "/tenants": if request.Method == "GET" || request.Method == "PUT" { if request.Method == "PUT" { From 5bd01f4818572ffb98f9330a39008418f032f4a4 Mon Sep 17 00:00:00 2001 From: forest Date: Mon, 3 May 2021 13:06:21 -0500 Subject: [PATCH 18/36] changes from testing greenhouse desktop --- main_client.go | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/main_client.go b/main_client.go index 4a25469..4746ed6 100644 --- a/main_client.go +++ b/main_client.go @@ -55,6 +55,10 @@ type LiveConfigUpdate struct { ServiceToLocalAddrMap map[string]string } +type ThresholdTenantInfo struct { + ThresholdServers []string +} + type clientAdminAPI struct{} // Client State @@ -101,7 +105,7 @@ func runClient(configFileName *string) { } greenhouseClient := http.Client{Timeout: time.Second * 10} - greenhouseURL := fmt.Sprintf("https://%s/api/thresholdservers", config.GreenhouseDomain) + greenhouseURL := fmt.Sprintf("https://%s/api/tenant_info", config.GreenhouseDomain) request, err := http.NewRequest("GET", greenhouseURL, nil) if err != nil { log.Fatal("invalid GreenhouseDomain '%s', can't create http request for %s", config.GreenhouseDomain, greenhouseURL) @@ -130,12 +134,12 @@ func runClient(configFileName *string) { if err != nil { log.Fatal("http read error GET '%s'", greenhouseURL) } - var ipPorts []string - err = json.Unmarshal(responseBytes, &ipPorts) + var tenantInfo ThresholdTenantInfo + err = json.Unmarshal(responseBytes, &tenantInfo) if err != nil { log.Fatal("http read error GET '%s'", greenhouseURL) } - for _, serverHostPort := range ipPorts { + for _, serverHostPort := range tenantInfo.ThresholdServers { clientServers = append(clientServers, makeServer(serverHostPort)) } } @@ -435,7 +439,7 @@ func (handler clientAdminAPI) ServeHTTP(response http.ResponseWriter, request *h ) http.Error( response, - fmt.Sprintf("502 tunnels request returned HTTP %d", tunnelsResponse.StatusCode), + fmt.Sprintf("502 tunnels request returned HTTP %d: %s", tunnelsResponse.StatusCode, string(tunnelsResponseBytes)), http.StatusBadGateway, ) return From 021cf1a1ae3e44238fc91f525d4d5f5bba97a832 Mon Sep 17 00:00:00 2001 From: forest Date: Wed, 5 May 2021 16:43:03 -0500 Subject: [PATCH 19/36] debugging stupid golang pointer crap causing wrong tunnel --- main_server.go | 23 +++++++++++++---------- tunnel-lib/server.go | 6 ++---- tunnel-lib/virtualaddr.go | 16 ++++++++++++---- 3 files changed, 27 insertions(+), 18 deletions(-) diff --git a/main_server.go b/main_server.go index e446353..e3ab616 100644 --- a/main_server.go +++ b/main_server.go @@ -721,19 +721,22 @@ func (s *ManagementHttpHandler) ServeHTTP(responseWriter http.ResponseWriter, re http.Error(responseWriter, errorMessage, statusCode) return } + } + } - bytes, err := json.Marshal(listenerConfigs) - if err != nil { - http.Error(responseWriter, "500 JSON Marshal Error", http.StatusInternalServerError) - return - } - - responseWriter.Header().Set("Content-Type", "application/json") - responseWriter.Write(bytes) + if request.Method == "PUT" || request.Method == "GET" { + bytes, err := json.Marshal(listenersByTenant[tenantId]) + if err != nil { + http.Error(responseWriter, "500 JSON Marshal Error", http.StatusInternalServerError) + return } + + responseWriter.Header().Set("Content-Type", "application/json") + responseWriter.Write(bytes) } else { - responseWriter.Header().Set("Allow", "PUT") - http.Error(responseWriter, "405 Method Not Allowed, try PUT", http.StatusMethodNotAllowed) + responseWriter.Header().Add("Allow", "PUT") + responseWriter.Header().Add("Allow", "GET") + http.Error(responseWriter, "405 Method Not Allowed, try GET or PUT", http.StatusMethodNotAllowed) } case "/ping": if request.Method == "GET" { diff --git a/tunnel-lib/server.go b/tunnel-lib/server.go index fac4dfb..01adcc5 100644 --- a/tunnel-lib/server.go +++ b/tunnel-lib/server.go @@ -203,8 +203,6 @@ func (s *Server) serveTCPConn(conn net.Conn) { } func (s *Server) handleTCPConn(conn net.Conn) error { - // TODO getListenerInfo should return the bytes we read to try to get teh hostname - // then we stream.write those right after the SendProxyProtocolv1 bit. log.Println(5) listenerInfo, sniHostname, connectionHeader := s.virtualAddrs.getListenerInfo(conn) @@ -222,7 +220,7 @@ func (s *Server) handleTCPConn(conn net.Conn) error { if listenerInfo.BackendService != "" { service = listenerInfo.BackendService } - log.Println(7) + log.Printf("7: dial(%s, %s)", listenerInfo.AssociatedClientId, service) stream, err := s.dial(listenerInfo.AssociatedClientId, service) log.Println(8) if err != nil { @@ -372,7 +370,7 @@ func (s *Server) dial(identifier string, service string) (net.Conn, error) { } if s.debugLog { - log.Printf("Server.proxy(): Sending control msg %+v\n", msg) + log.Printf("Server.proxy(): Sending control msg %+v to %s \n", msg, identifier) } // ask client to open a session to us, so we can accept it diff --git a/tunnel-lib/virtualaddr.go b/tunnel-lib/virtualaddr.go index 02f140c..e5dc7f7 100644 --- a/tunnel-lib/virtualaddr.go +++ b/tunnel-lib/virtualaddr.go @@ -288,7 +288,8 @@ func (vaddr *vaddrStorage) getListenerInfo(conn net.Conn) (*ListenerInfo, string if err == nil && listenHostMatches && listenPortMatches { recordSpecificity := -10 - var mostSpecificMatchingBackend *ListenerInfo = nil + mostSpecificMatchingBackend := ListenerInfo{} + hasMatchingBackend := false for _, backend := range listener.backends { globToUse := backend.HostnameGlob if globToUse == "" { @@ -297,14 +298,21 @@ func (vaddr *vaddrStorage) getListenerInfo(conn net.Conn) (*ListenerInfo, string numberOfPeriods := len(vaddr.dotRegex.FindAllString(globToUse, -1)) numberOfGlobs := len(vaddr.globRegex.FindAllString(globToUse, -1)) specificity := numberOfPeriods - numberOfGlobs - //log.Printf("%d > %d && Glob(%s, %s) (%t)\n", specificity, recordSpecificity, globToUse, hostname, Glob(globToUse, hostname)) + log.Printf("%d > %d && Glob(%s, %s)->(%t)\n", specificity, recordSpecificity, globToUse, hostname, Glob(globToUse, hostname)) if specificity > recordSpecificity && Glob(globToUse, hostname) { recordSpecificity = specificity - mostSpecificMatchingBackend = &backend + mostSpecificMatchingBackend = backend + hasMatchingBackend = true + log.Printf("mostSpecificMatchingBackend: %s->%s\n", mostSpecificMatchingBackend.AssociatedClientId, mostSpecificMatchingBackend.BackendService) } } - return mostSpecificMatchingBackend, hostname, connectionHeader[:n] + if hasMatchingBackend { + return &mostSpecificMatchingBackend, hostname, connectionHeader[:n] + } else { + return nil, hostname, connectionHeader[:n] + } + } } From af7481739a7b7e5a75f0af5511e0a69223c6c162 Mon Sep 17 00:00:00 2001 From: forest Date: Fri, 7 May 2021 15:07:23 -0500 Subject: [PATCH 20/36] allow users to define tunnels for disconnected nodes --- main_server.go | 23 ++++++++++++++--------- tunnel-lib/server.go | 1 + 2 files changed, 15 insertions(+), 9 deletions(-) diff --git a/main_server.go b/main_server.go index e3ab616..9b9ff98 100644 --- a/main_server.go +++ b/main_server.go @@ -300,15 +300,20 @@ func setListeners(tenantId string, listenerConfigs []ListenerConfig) (int, strin currentListenersThatCanKeepRunning := make([]ListenerConfig, 0) newListenersThatHaveToBeAdded := make([]ListenerConfig, 0) - for _, newListenerConfig := range listenerConfigs { - clientState, everHeardOfClientBefore := clientStatesByTenant[tenantId][newListenerConfig.ClientId] - if !everHeardOfClientBefore { - return http.StatusNotFound, fmt.Sprintf("Client %s Not Found", newListenerConfig.ClientId) - } - if clientState.CurrentState != tunnel.ClientConnected.String() { - return http.StatusNotFound, fmt.Sprintf("Client %s is not connected it is %s", newListenerConfig.ClientId, clientState.CurrentState) - } - } + // I think its probably a good idea to allow the user to create tunnels for nodes that aren't connected + // If a node has a temporary outage (or a threshold server respawns during a node outage) + // that should not prevent the user from setting the tunnels + // If the server tries to dial a disconnected node, it will simply fail dailing with an error. + + // for _, newListenerConfig := range listenerConfigs { + // clientState, everHeardOfClientBefore := clientStatesByTenant[tenantId][newListenerConfig.ClientId] + // if !everHeardOfClientBefore { + // return http.StatusNotFound, fmt.Sprintf("Client %s Not Found", newListenerConfig.ClientId) + // } + // if clientState.CurrentState != tunnel.ClientConnected.String() { + // return http.StatusNotFound, fmt.Sprintf("Client %s is not connected it is %s", newListenerConfig.ClientId, clientState.CurrentState) + // } + // } for _, existingListener := range listenersByTenant[tenantId] { canKeepRunning := false diff --git a/tunnel-lib/server.go b/tunnel-lib/server.go index 01adcc5..96f9526 100644 --- a/tunnel-lib/server.go +++ b/tunnel-lib/server.go @@ -224,6 +224,7 @@ func (s *Server) handleTCPConn(conn net.Conn) error { stream, err := s.dial(listenerInfo.AssociatedClientId, service) log.Println(8) if err != nil { + log.Printf("Server.handleTCPConn(): failed to dial %s on client %s: %s\n", service, listenerInfo.AssociatedClientId, err) return err } From 9323c24740375bfdc791380c907c7de05f596c64 Mon Sep 17 00:00:00 2001 From: forest Date: Tue, 11 May 2021 17:57:10 -0500 Subject: [PATCH 21/36] cleaning up and working on implementing threshold test mode --- main_client.go | 121 ++++++++++++++++++++++++++++ tunnel-lib/client.go | 4 +- tunnel-lib/proxy.go | 18 ----- tunnel-lib/tunneltest/tunneltest.go | 10 +-- 4 files changed, 125 insertions(+), 28 deletions(-) diff --git a/main_client.go b/main_client.go index 4746ed6..1d6247e 100644 --- a/main_client.go +++ b/main_client.go @@ -2,12 +2,16 @@ package main import ( "bytes" + "crypto/rand" + "crypto/rsa" "crypto/tls" "crypto/x509" + "crypto/x509/pkix" "encoding/json" "fmt" "io/ioutil" "log" + "math/big" "net" "net/http" "net/url" @@ -19,6 +23,7 @@ import ( "time" tunnel "git.sequentialread.com/forest/threshold/tunnel-lib" + "git.sequentialread.com/forest/threshold/tunnel-lib/proto" ) type ClientConfig struct { @@ -66,6 +71,11 @@ var clientServers []ClientServer var tlsClientConfig *tls.Config var serviceToLocalAddrMap *map[string]string +var isTestMode bool +var testModeListeners map[string]ListenerConfig +var testModeTLSConfig tls.Config +var testTokens []string + func runClient(configFileName *string) { configBytes := getConfigBytes(configFileName) @@ -273,6 +283,19 @@ func runClient(configFileName *string) { return localAddr, nil } + productionProxyFunc := (&tunnel.TCPProxy{ + FetchLocalAddr: fetchLocalAddr, + DebugLog: config.DebugLog, + }).Proxy + + proxyFunc := func(remote net.Conn, msg *proto.ControlMessage) { + if isTestMode { + handleTestConnection(remote, msg) + } else { + productionProxyFunc(remote, msg) + } + } + for _, server := range clientServers { clientStateChanges := make(chan *tunnel.ClientStateChange) tunnelClientConfig := &tunnel.ClientConfig{ @@ -280,6 +303,7 @@ func runClient(configFileName *string) { Identifier: config.ClientId, ServerAddr: server.ServerHostPort, FetchLocalAddr: fetchLocalAddr, + Proxy: proxyFunc, Dial: dialFunction, StateChanges: clientStateChanges, } @@ -463,3 +487,100 @@ func (handler clientAdminAPI) ServeHTTP(response http.ResponseWriter, request *h } } + +func handleTestConnection(remote net.Conn, msg *proto.ControlMessage) { + listenerInfo, hasListenerInfo := testModeListeners[msg.Service] + if !hasListenerInfo { + remote.Close() + } else if listenerInfo.ListenHostnameGlob != "" && listenerInfo.ListenHostnameGlob != "*" { + // TODO make greenhouse-desktop always use HAPROXY proxy protocol with Caddy + // so caddy can get the real remote IP + if listenerInfo.ListenPort == 80 { + requestBuffer := make([]byte, 1024) + bytesRead, err := remote.Read(requestBuffer) + if err != nil { + remote.Close() + } else { + result := regexp.MustCompile("GET /([^ ]+) HTTP/1.1").FindStringSubmatch(string(requestBuffer[:bytesRead])) + if result != nil && len(result) == 2 { + testToken := result[1] + testTokens = append(testTokens, testToken) + remote.Write([]byte(fmt.Sprintf(`HTTP/1.1 200 OK +Content-Type: text/plain + +%s`, testToken))) + // TODO add remote.RemoteAddr().String() + remote.Close() + } + } + } else { + remote_tls := tls.Server(remote, &testModeTLSConfig) + err := remote_tls.Handshake() + if err != nil { + remote_tls.Close() + return + } + requestBuffer := make([]byte, 1024) + bytesRead, err := remote_tls.Read(requestBuffer) + if err != nil { + remote_tls.Close() + return + } + testToken := string(requestBuffer[:bytesRead]) + testTokens = append(testTokens, testToken) + remote_tls.Write([]byte(testToken)) + remote_tls.Close() + } + } else { + requestBuffer := make([]byte, 1024) + bytesRead, err := remote.Read(requestBuffer) + if err != nil { + remote.Close() + return + } + testToken := string(requestBuffer[:bytesRead]) + testTokens = append(testTokens, testToken) + remote.Write([]byte(testToken)) + remote.Close() + } +} + +// https://gist.github.com/shivakar/cd52b5594d4912fbeb46 +// create a bogus TLS key pair for the test server to use -- the test client will use InsecureSkipVerify +func GenerateTestX509Cert() (tls.Certificate, error) { + now := time.Now() + template := &x509.Certificate{ + SerialNumber: big.NewInt(now.Unix()), + Subject: pkix.Name{ + CommonName: "threshold-test-certificate.example.com", + Country: []string{"USA"}, + Organization: []string{"example.com"}, + OrganizationalUnit: []string{"threshold-test-certificate"}, + }, + NotBefore: now, + NotAfter: now.AddDate(99, 0, 0), // Valid for long time (99 years) + SubjectKeyId: []byte{113, 117, 105, 99, 107, 115, 101, 114, 118, 101}, // nonsense bytes + BasicConstraintsValid: true, + IsCA: true, + ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, + KeyUsage: x509.KeyUsageKeyEncipherment | + x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign, + } + + priv, err := rsa.GenerateKey(rand.Reader, 2048) + if err != nil { + return tls.Certificate{}, err + } + + cert, err := x509.CreateCertificate(rand.Reader, template, template, + priv.Public(), priv) + if err != nil { + return tls.Certificate{}, err + } + + var outCert tls.Certificate + outCert.Certificate = append(outCert.Certificate, cert) + outCert.PrivateKey = priv + + return outCert, nil +} diff --git a/tunnel-lib/client.go b/tunnel-lib/client.go index 515a61e..92e9c08 100644 --- a/tunnel-lib/client.go +++ b/tunnel-lib/client.go @@ -199,9 +199,7 @@ func NewClient(cfg *ClientConfig) (*Client, error) { proxy := cfg.Proxy if proxy == nil { - var f ProxyFuncs - f.TCP = (&TCPProxy{FetchLocalAddr: cfg.FetchLocalAddr, DebugLog: cfg.DebugLog}).Proxy - proxy = Proxy(f) + proxy = (&TCPProxy{FetchLocalAddr: cfg.FetchLocalAddr, DebugLog: cfg.DebugLog}).Proxy } var bo Backoff = newForeverBackoff() diff --git a/tunnel-lib/proxy.go b/tunnel-lib/proxy.go index 7447bf5..8f3634e 100644 --- a/tunnel-lib/proxy.go +++ b/tunnel-lib/proxy.go @@ -13,24 +13,6 @@ import ( // ProxyFunc is responsible for forwarding a remote connection to local server and writing the response back. type ProxyFunc func(remote net.Conn, msg *proto.ControlMessage) -// ProxyFuncs is a collection of ProxyFunc. -type ProxyFuncs struct { - // TCP is custom implementation of TCP proxing. - TCP ProxyFunc -} - -// Proxy returns a ProxyFunc that uses custom function if provided, otherwise falls back to DefaultProxyFuncs. -func Proxy(p ProxyFuncs) ProxyFunc { - return func(remote net.Conn, msg *proto.ControlMessage) { - if p.TCP == nil { - panic("TCP handler is required for Proxy") - } - - // I removed all the other handlers that are not TCP 😇 - p.TCP(remote, msg) - } -} - // Join copies data between local and remote connections. // It reads from one connection and writes to the other. // It's a building block for ProxyFunc implementations. diff --git a/tunnel-lib/tunneltest/tunneltest.go b/tunnel-lib/tunneltest/tunneltest.go index 645aba7..333da5b 100644 --- a/tunnel-lib/tunneltest/tunneltest.go +++ b/tunnel-lib/tunneltest/tunneltest.go @@ -267,16 +267,12 @@ func (tt *TunnelTest) serveSingle(ident string, t *Tunnel) (bool, error) { } localAddr := l.Addr().String() - httpProxy := &tunnel.HTTPProxy{LocalAddr: localAddr} tcpProxy := &tunnel.TCPProxy{FetchLocalAddr: tt.fetchLocalAddr} cfg := &tunnel.ClientConfig{ - Identifier: ident, - ServerAddr: tt.ServerAddr().String(), - Proxy: tunnel.Proxy(tunnel.ProxyFuncs{ - HTTP: httpProxy.Proxy, - TCP: tcpProxy.Proxy, - }), + Identifier: ident, + ServerAddr: tt.ServerAddr().String(), + Proxy: tcpProxy.Proxy, StateChanges: t.StateChanges, Debug: testing.Verbose(), } From 5546ce31bd5f4f9af11fb1ef81e14db3df021c73 Mon Sep 17 00:00:00 2001 From: forest Date: Sun, 16 May 2021 09:50:17 -0500 Subject: [PATCH 22/36] support dialing unix sockets for local servers, support PROXY proto for self-test --- go.mod | 2 +- go.sum | 2 ++ main_client.go | 43 ++++++++++++++++++++++++++++++++++++++---- tunnel-lib/tcpproxy.go | 10 ++++++++-- 4 files changed, 50 insertions(+), 7 deletions(-) diff --git a/go.mod b/go.mod index b5eff1a..99ba466 100644 --- a/go.mod +++ b/go.mod @@ -3,7 +3,7 @@ module git.sequentialread.com/forest/threshold go 1.14 require ( - github.com/armon/go-proxyproto v0.0.0-20180202201750-5b7edb60ff5f + github.com/armon/go-proxyproto v0.0.0-20210323213023-7e956b284f0a github.com/cenkalti/backoff v2.1.0+incompatible github.com/gorilla/websocket v1.4.0 github.com/hashicorp/yamux v0.0.0-20181012175058-2f1d1f20f75d diff --git a/go.sum b/go.sum index 6e6c8f7..d239f7a 100644 --- a/go.sum +++ b/go.sum @@ -2,6 +2,8 @@ git.sequentialread.com/forest/tunnel v0.0.0-20170601195443-35a8b95662bf h1:2flo/ git.sequentialread.com/forest/tunnel v0.0.0-20170601195443-35a8b95662bf/go.mod h1:i+PvDDsWjggoCQOO8bGJJKRB9qfxmHk5yzIEA/h8dzg= github.com/armon/go-proxyproto v0.0.0-20180202201750-5b7edb60ff5f h1:SaJ6yqg936TshyeFZqQE+N+9hYkIeL9AMr7S4voCl10= github.com/armon/go-proxyproto v0.0.0-20180202201750-5b7edb60ff5f/go.mod h1:QmP9hvJ91BbJmGVGSbutW19IC0Q9phDCLGaomwTJbgU= +github.com/armon/go-proxyproto v0.0.0-20210323213023-7e956b284f0a h1:AP/vsCIvJZ129pdm9Ek7bH7yutN3hByqsMoNrWAxRQc= +github.com/armon/go-proxyproto v0.0.0-20210323213023-7e956b284f0a/go.mod h1:QmP9hvJ91BbJmGVGSbutW19IC0Q9phDCLGaomwTJbgU= github.com/cenkalti/backoff v2.1.0+incompatible h1:FIRvWBZrzS4YC7NT5cOuZjexzFvIr+Dbi6aD1cZaNBk= github.com/cenkalti/backoff v2.1.0+incompatible/go.mod h1:90ReRw6GdpyfrHakVjL/QHaoyV4aDUVVkXQJJJ3NXXM= github.com/gorilla/websocket v1.4.0 h1:WDFjx/TMzVgy9VdMMQi2K2Emtwi2QcUQsztZ/zLaH/Q= diff --git a/main_client.go b/main_client.go index 1d6247e..d2a3ddf 100644 --- a/main_client.go +++ b/main_client.go @@ -24,6 +24,7 @@ import ( tunnel "git.sequentialread.com/forest/threshold/tunnel-lib" "git.sequentialread.com/forest/threshold/tunnel-lib/proto" + proxyprotocol "github.com/armon/go-proxyproto" ) type ClientConfig struct { @@ -73,7 +74,7 @@ var serviceToLocalAddrMap *map[string]string var isTestMode bool var testModeListeners map[string]ListenerConfig -var testModeTLSConfig tls.Config +var testModeTLSConfig *tls.Config var testTokens []string func runClient(configFileName *string) { @@ -403,6 +404,28 @@ func runClientAdminApi(config ClientConfig) { // client admin api handler for /liveconfig over unix socket func (handler clientAdminAPI) ServeHTTP(response http.ResponseWriter, request *http.Request) { switch path.Clean(request.URL.Path) { + case "/start_test": + isTestMode = true + testTokens = []string{} + if testModeTLSConfig == nil { + certificate, err := GenerateTestX509Cert() + if err != nil { + log.Printf("clientAdminAPI: GenerateTestX509Cert failed: %+v\n\n", err) + http.Error(response, "500 GenerateTestX509Cert failed", http.StatusInternalServerError) + return + } + testModeTLSConfig = &tls.Config{ + Certificates: []tls.Certificate{certificate}, + } + testModeTLSConfig.BuildNameToCertificate() + } + response.Write([]byte("OK")) + case "/end_test": + isTestMode = false + response.Header().Set("Content-Type", "text/plain") + for _, testToken := range testTokens { + response.Write([]byte(fmt.Sprintln(testToken))) + } case "/liveconfig": if request.Method == "PUT" { requestBytes, err := ioutil.ReadAll(request.Body) @@ -474,6 +497,12 @@ func (handler clientAdminAPI) ServeHTTP(response http.ResponseWriter, request *h serviceToLocalAddrMap = &configUpdate.ServiceToLocalAddrMap } + // cache the listeners locally for use in test mode. + testModeListeners = map[string]ListenerConfig{} + for _, listener := range configUpdate.Listeners { + testModeListeners[listener.BackEndService] = listener + } + response.Header().Add("content-type", "application/json") response.WriteHeader(http.StatusOK) response.Write(requestBytes) @@ -483,16 +512,22 @@ func (handler clientAdminAPI) ServeHTTP(response http.ResponseWriter, request *h http.Error(response, "405 method not allowed, try PUT", http.StatusMethodNotAllowed) } default: - http.Error(response, "404 not found, try PUT /liveconfig", http.StatusNotFound) + http.Error(response, "404 not found, try PUT /liveconfig or PUT/GET /testmode", http.StatusNotFound) } } func handleTestConnection(remote net.Conn, msg *proto.ControlMessage) { listenerInfo, hasListenerInfo := testModeListeners[msg.Service] + log.Printf("handleTestConnection: %s (%s, %d)", msg.Service, listenerInfo.ListenHostnameGlob, listenerInfo.ListenPort) if !hasListenerInfo { remote.Close() - } else if listenerInfo.ListenHostnameGlob != "" && listenerInfo.ListenHostnameGlob != "*" { + return + } + if listenerInfo.HaProxyProxyProtocol { + remote = proxyprotocol.NewConn(remote, time.Second*5) + } + if listenerInfo.ListenHostnameGlob != "" && listenerInfo.ListenHostnameGlob != "*" { // TODO make greenhouse-desktop always use HAPROXY proxy protocol with Caddy // so caddy can get the real remote IP if listenerInfo.ListenPort == 80 { @@ -514,7 +549,7 @@ Content-Type: text/plain } } } else { - remote_tls := tls.Server(remote, &testModeTLSConfig) + remote_tls := tls.Server(remote, testModeTLSConfig) err := remote_tls.Handshake() if err != nil { remote_tls.Close() diff --git a/tunnel-lib/tcpproxy.go b/tunnel-lib/tcpproxy.go index ce887e3..aeff546 100644 --- a/tunnel-lib/tcpproxy.go +++ b/tunnel-lib/tcpproxy.go @@ -3,6 +3,7 @@ package tunnel import ( "log" "net" + "strings" "git.sequentialread.com/forest/threshold/tunnel-lib/proto" ) @@ -34,9 +35,14 @@ func (p *TCPProxy) Proxy(remote net.Conn, msg *proto.ControlMessage) { //log.Debug("Dialing local server: %q", localAddr) //fmt.Printf("Dialing local server: %q\n\n", localAddr) - local, err := net.DialTimeout("tcp", localAddr, defaultTimeout) + network := "tcp" + if strings.HasPrefix(localAddr, "unix//") { + network = "unix" + localAddr = strings.TrimPrefix(localAddr, "unix//") + } + local, err := net.DialTimeout(network, localAddr, defaultTimeout) if err != nil { - log.Println("TCPProxy.Proxy(): Dialing local server %q failed: %s", localAddr, err) + log.Printf("TCPProxy.Proxy(): Dialing local server %s failed: %s", localAddr, err) return } From 85552b5516c3c955b580e4bd58938ec8ef30c291 Mon Sep 17 00:00:00 2001 From: forest Date: Tue, 18 May 2021 18:52:31 -0500 Subject: [PATCH 23/36] I don't know if this data matters or not but I figured if it does, might be a good idea to make it random. --- main_client.go | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/main_client.go b/main_client.go index d2a3ddf..b2b45e4 100644 --- a/main_client.go +++ b/main_client.go @@ -584,6 +584,10 @@ Content-Type: text/plain // create a bogus TLS key pair for the test server to use -- the test client will use InsecureSkipVerify func GenerateTestX509Cert() (tls.Certificate, error) { now := time.Now() + + subjectKeyIDByteSlice := make([]byte, 10) + rand.Read(subjectKeyIDByteSlice) + template := &x509.Certificate{ SerialNumber: big.NewInt(now.Unix()), Subject: pkix.Name{ @@ -593,8 +597,8 @@ func GenerateTestX509Cert() (tls.Certificate, error) { OrganizationalUnit: []string{"threshold-test-certificate"}, }, NotBefore: now, - NotAfter: now.AddDate(99, 0, 0), // Valid for long time (99 years) - SubjectKeyId: []byte{113, 117, 105, 99, 107, 115, 101, 114, 118, 101}, // nonsense bytes + NotAfter: now.AddDate(99, 0, 0), // Valid for long time (99 years) + SubjectKeyId: subjectKeyIDByteSlice, BasicConstraintsValid: true, IsCA: true, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, From 63b09a552cf2bee588a6204b8b54f7496eb29e4c Mon Sep 17 00:00:00 2001 From: forest Date: Thu, 27 May 2021 18:09:37 -0500 Subject: [PATCH 24/36] first try at adding forward proxy support to threshold client --- tunnel-lib/client.go | 140 +++++++++++++++++++++++++++++--- tunnel-lib/proto/control_msg.go | 1 + 2 files changed, 129 insertions(+), 12 deletions(-) diff --git a/tunnel-lib/client.go b/tunnel-lib/client.go index 92e9c08..2ed3471 100644 --- a/tunnel-lib/client.go +++ b/tunnel-lib/client.go @@ -8,6 +8,7 @@ import ( "log" "net" "net/http" + "strconv" "sync" "sync/atomic" "time" @@ -97,6 +98,8 @@ type Client struct { // redialBackoff is used to reconnect in exponential backoff intervals redialBackoff Backoff + + incomingForwardProxyConnections chan net.Conn } // ClientConfig defines the configuration for the Client @@ -126,7 +129,7 @@ type ClientConfig struct { // where you can provide your local server selection or communication rules. Proxy ProxyFunc - // Dial provides custom transport layer for client server communication. + // Dial provides custom transport layer for communication between the threshold client and threshold server. // // If nil, default implementation is to return net.Dial("tcp", address). // @@ -504,7 +507,29 @@ func (c *Client) connect(identifier, serverAddr string) error { c.startNotifyIfNeeded() - return c.listenControl(ct) + // inline immediately invoked function expression to use defer + return (func() error { + c.ctrlWg.Add(1) + defer c.ctrlWg.Done() + + c.incomingForwardProxyConnections = make(chan net.Conn) + c.changeState(ClientConnected, nil) + + var err error + select { + case err = <-async(func() error { return c.listenControl(ct) }): + log.Printf("Client.listenControl() exited with: %+v\n", err) + case err = <-async(func() error { return c.listenForwardProxy(ct) }): + log.Printf("Client.listenForwardProxy() exited with: %+v\n", err) + } + + c.session.GoAway() + c.session.Close() + ct.Close() + c.changeState(ClientDisconnected, err) + return err + + })() } func (c *Client) dial(serverAddr string) (net.Conn, error) { @@ -516,19 +541,9 @@ func (c *Client) dial(serverAddr string) (net.Conn, error) { } func (c *Client) listenControl(ct *control) error { - c.ctrlWg.Add(1) - defer c.ctrlWg.Done() - - c.changeState(ClientConnected, nil) - for { var msg proto.ControlMessage if err := ct.dec.Decode(&msg); err != nil { - c.reqWg.Wait() // wait until all requests are finished - c.session.GoAway() - c.session.Close() - c.changeState(ClientDisconnected, err) - return fmt.Errorf("failure decoding control message: %s", err) } @@ -551,3 +566,104 @@ func (c *Client) listenControl(ct *control) error { }() } } + +func (c *Client) HandleForwardProxy(conn net.Conn) error { + if c.state != ClientConnected { + conn.Close() + return errors.New("client is disconnected, can't accept any forward proxy connections") + } else { + c.incomingForwardProxyConnections <- conn + return nil + } +} + +func (c *Client) listenForwardProxy(ct *control) error { + + forwardProxyConnectionId := 0 + for { + conn := <-c.incomingForwardProxyConnections + + forwardProxyConnectionId++ + + if c.config.DebugLog { + log.Printf("Client.listenForwardProxy(): Received incoming forward proxy connection %d\n", forwardProxyConnectionId) + } + + err := ct.send(proto.ControlMessage{Action: proto.RequestForwardProxy}) + if err != nil { + return fmt.Errorf("failure seding control message: %s", err) + } + + if c.config.DebugLog { + log.Printf("Client.listenForwardProxy(): forward proxy connection %d: sent RequestForwardProxy to server \n", forwardProxyConnectionId) + } + + remoteConn, err := c.session.Accept() + if err != nil { + return err + } + + if c.config.DebugLog { + log.Printf("Client.listenForwardProxy(): forward proxy connection %d: accepted yamux session \n", forwardProxyConnectionId) + } + + go func() { + BlockingBidirectionalPipe(conn, remoteConn, "from client", "to SOCKS server", strconv.Itoa(forwardProxyConnectionId), c.config.DebugLog) + conn.Close() + remoteConn.Close() + }() + } +} + +func BlockingBidirectionalPipe(conn1, conn2 net.Conn, name1, name2 string, connectionId string, debugLog bool) { + chanFromConn := func(conn net.Conn, name, connectionId string) chan []byte { + c := make(chan []byte) + + go func() { + b := make([]byte, 1024) + + for { + n, err := conn.Read(b) + if n > 0 { + res := make([]byte, n) + // Copy the buffer so it doesn't get changed while read by the recipient. + copy(res, b[:n]) + c <- res + } + if err != nil { + log.Printf("%s %s read error %s\n", connectionId, name, err) + c <- nil + break + } + } + }() + + return c + } + + chan1 := chanFromConn(conn1, fmt.Sprint(name1, "->", name2), connectionId) + chan2 := chanFromConn(conn2, fmt.Sprint(name2, "->", name1), connectionId) + + for { + select { + case b1 := <-chan1: + if b1 == nil { + if debugLog { + log.Printf("connection %s %s EOF\n", connectionId, name1) + } + return + } else { + conn2.Write(b1) + } + case b2 := <-chan2: + if b2 == nil { + if debugLog { + log.Printf("connection %s %s EOF\n", connectionId, name2) + } + return + } else { + conn1.Write(b2) + } + } + } +} diff --git a/tunnel-lib/proto/control_msg.go b/tunnel-lib/proto/control_msg.go index a92700f..f1135b7 100644 --- a/tunnel-lib/proto/control_msg.go +++ b/tunnel-lib/proto/control_msg.go @@ -12,4 +12,5 @@ type Action int // ControlMessage actions. const ( RequestClientSession Action = iota + 1 + RequestForwardProxy Action = iota + 2 ) From eba3f519253021ff0bd7e5581321a754d10687fc Mon Sep 17 00:00:00 2001 From: forest Date: Wed, 9 Jun 2021 17:16:47 -0500 Subject: [PATCH 25/36] add forward proxy listener and update readme --- README.md | 44 +++++++++++++++++++++----------------- main_client.go | 50 ++++++++++++++++++++++++++++++++++++++++---- tunnel-lib/client.go | 2 +- 3 files changed, 72 insertions(+), 24 deletions(-) diff --git a/README.md b/README.md index 976468b..7e80666 100644 --- a/README.md +++ b/README.md @@ -1,13 +1,17 @@ -## threshold +## threshold 🏔️⛰️🛤️⛰️🏔️ -Public Internet facing gateway (TCP reverse tunnel) for server.garden. +Threshold was created to make self-hosting websites, email, and other services radically easier. + +Threshold implements a public-internet-facing gateway (TCP reverse tunnel & SOCKS5 forward proxy) for self-hosted servers. + +The [greenhouse cloud service](https://git.sequentialread.com/forest/greenhouse) was developed in order to make threshold more easily accessible to more people. Greenhouse operates the server side of threshold as a service, charging $0.01 per GB of bandwidth. ![](readme/splash.png) -This project was originally forked from https://github.com/koding/tunnel +Threshold server is designed to be a **relatively untrusted** service, in other words, the user doesn't need to place much trust in the environment where the server runs. It's designed so that the server operator can't spy on you. This makes it uniquely suited to bridge the "ownership vs capability" gap between a self-hosted server/homelab/datacenter and a 3rd-party public cloud environment, hence the name threshold. -It is intended to be used to make it easier for non-tech-savvy people to host web services that are avaliable on the public internet. +This project was originally forked from https://github.com/koding/tunnel This repository only includes the application that does the tunneling part. It does not include any other management or automation tools. @@ -19,14 +23,15 @@ This diagram was created with https://app.diagrams.net/. To edit it, download the diagram file and edit it with the https://app.diagrams.net/ web application, or you may run the application from [source](https://github.com/jgraph/drawio) if you wish. - ### How it is intended to be used: -1. An automated tool creates a cloud instance and installs and configures the tunnel server on it. -1. An automated tool installs the tunnel client on the self-hoster's server computer. -1. An automated tool calls the `PUT /tunnels` api on the tunnel server's Management Port, and sends a JSON file describing which ports should be opened on the tunnel server, which client they should be tunneled to, and which service on the client they should be tunneled to, as well as whether or not the HAProxy "PROXY" protocol should be used. This connection can use TLS Client Authentication. -1. The tunnel client connects to the tunnel server on the Tunnel Control Port. This connection can use TLS Client Authentication. This connection will be held open and re-created if dropped. -1. An internet user connects to the tunnel server on one of the ports defined in the JSON. The internet user's request is tunneled through the original connection from the tunnel client, and then proxied to the web server software running on the self-hoster's server computer. +1. An automated tool creates a cloud instance and installs and configures the threshold server on it. +1. An automated tool installs the threshold client on the self-hoster's server computer. +1. An automated tool calls the `PUT /tunnels` api on the threshold server's Management Port, and sends a JSON file describing which ports should be opened on the threshold server, which client they should be tunneled to, and which service on the client they should be tunneled to, as well as whether or not the HAProxy "PROXY" protocol should be used. This connection can use TLS Client Authentication. +1. The threshold client connects to the threshold server on the Tunnel Control Port. This connection can use TLS Client Authentication. This connection will be held open and re-created if dropped. +1. An internet user connects to the threshold server on one of the ports defined in the JSON. The internet user's request is tunneled through the original connection from the threshold client, and then proxied to the web server software running on the self-hoster's server computer. +1. (OPTIONAL) The server operator installs software (for example, email server) which requires outgoing requests to "come from" the same IP address that the server is listening for connections at. +1. The email server or other software connects to the threshold client for SOCKS5 forward proxy. The threshold client forwards this connection through the existing tunnel connection to the threshold server (secured by TLS), then the threshold server handles the SOCKS5 connection and proxies it to the destination requested by the email server or other software. ### Output from Usage example showing how it works: @@ -96,10 +101,10 @@ Note how the listener sees the original source IP and port, not the source IP an I have a few requirements for this system. -* It should be 100% automatable. It is intended to be used in a situation where it is unreasonable to ask the user to configure thier router, for example, they don't know how, they don't want to, or they are not allowed to (For example they live in a dorm where the University manages the network). -* Users have control over their own data. We do not entrust cloud providers or 3rd parties with our data, TLS keys/certificates, etc. In terms of every day usage, this is a TLS connection from an internet user directly to the self-hoster's computer. It is opaque to the cloud provider. - * If the cloud provider wants to launch a Man in the Middle attack, even if they could secretly obtain a trusted cert to use, it will not be easy to hide from the user as long as the user (or software that they installed) is anticipating it. -* It should support Failover/High Avaliability of services. Therefore, it needs to be able to have multiple tunnel clients connected at once, which can be hot-swapped via a Management API. +* It should be 100% automatable. It is intended to be used in a situation where it is unreasonable to ask the user to perform any sort of advanced manual configuration. +* Users have control over their own data. We do not entrust cloud providers or 3rd parties with our data, even those who are hosting our threshold server. TLS keys/certificates, security-relevant configurations, etc only exist on the user-controlled computer. The cloud provider doesn't get access to any information or capability beyond what the user's ISP (Internet Service Provider) would normally have. + * If the cloud provider wants to launch a Man in the Middle attack against the threshold user, they will run into the same problems that an ISP would. +* It should support Failover/High Avaliability of services. Therefore, it needs to be able to have multiple tunnel clients connected at once, which can be hot-swapped via a management API. ### What did you add on top of the koding/tunnel package? @@ -114,15 +119,16 @@ I have a few requirements for this system. * Introduced concept of a "service" string instead of port number, so the client decides what ports to connect to, not the server. * Added support TLS SNI based virtual hosts. (Hostname based routing) * Fixed various bugs related to connection lifecycle. +* Added a tunneled SOCKS5 proxy to support applications like email servers which need to be able to dial out from the same IP address that they recieve connections at. ### How to build ``` -go build -o tunnel -tags netgo +go build -o threshold +``` -# -tags netgo? what? -# this is a work around for dynamic linking on alpine linux -# see: https://stackoverflow.com/questions/36279253/go-compiled-binary-wont-run-in-an-alpine-docker-container-on-ubuntu-host +### How to build the docker image: -docker build -t sequentialread/tunnel:0.0.1 . +``` +./build-docker.sh ``` diff --git a/main_client.go b/main_client.go index b2b45e4..9c601f0 100644 --- a/main_client.go +++ b/main_client.go @@ -33,6 +33,7 @@ type ClientConfig struct { GreenhouseDomain string GreenhouseAPIToken string GreenhouseThresholdPort int + ForwardProxyListenAddress string ServerAddr string Servers []string ServiceToLocalAddrMap *map[string]string @@ -90,6 +91,17 @@ func runClient(configFileName *string) { if config.GreenhouseThresholdPort == 0 { config.GreenhouseThresholdPort = 9056 } + if config.ForwardProxyListenAddress == "" { + config.ForwardProxyListenAddress = "127.0.0.1:8000" + } + forwardProxyListenAddress, err := net.ResolveTCPAddr("tcp", config.ForwardProxyListenAddress) + if err != nil { + log.Fatalf("runClient(): can't net.ResolveTCPAddr(forwardProxyListenAddress) because %s \n", err) + } + forwardProxyListener, err := net.ListenTCP("tcp", forwardProxyListenAddress) + if err != nil { + log.Fatalf("runClient(): can't net.ListenTCP(\"tcp\", forwardProxyListenAddress) because %s \n", err) + } clientServers = []ClientServer{} makeServer := func(hostPort string) ClientServer { @@ -104,6 +116,8 @@ func runClient(configFileName *string) { } } + serverListToLog := "" + if config.GreenhouseDomain != "" { if config.ServerAddr != "" { log.Fatal("config contains both GreenhouseDomain and ServerAddr, only use one or the other") @@ -123,6 +137,7 @@ func runClient(configFileName *string) { } request.Header.Add("Authorization", fmt.Sprintf("Bearer %s", config.GreenhouseAPIToken)) + hostPortStringsToLog := []string{} response, err := greenhouseClient.Do(request) if err != nil || response.StatusCode != 200 { if err == nil { @@ -138,7 +153,9 @@ func runClient(configFileName *string) { log.Fatalf("Failed to lookup GreenhouseDomain '%s'", config.GreenhouseDomain) } for _, ip := range ips { - clientServers = append(clientServers, makeServer(fmt.Sprintf("%s:%d", ip, config.GreenhouseThresholdPort))) + serverHostPort := fmt.Sprintf("%s:%d", ip, config.GreenhouseThresholdPort) + clientServers = append(clientServers, makeServer(serverHostPort)) + hostPortStringsToLog = append(hostPortStringsToLog, serverHostPort) } } else { responseBytes, err := ioutil.ReadAll(response.Body) @@ -150,11 +167,15 @@ func runClient(configFileName *string) { if err != nil { log.Fatal("http read error GET '%s'", greenhouseURL) } + for _, serverHostPort := range tenantInfo.ThresholdServers { clientServers = append(clientServers, makeServer(serverHostPort)) + hostPortStringsToLog = append(hostPortStringsToLog, serverHostPort) } } + serverListToLog = fmt.Sprintf("%s (%s)", config.GreenhouseDomain, strings.Join(hostPortStringsToLog, ", ")) + } else if config.Servers != nil && len(config.Servers) > 0 { if config.ServerAddr != "" { log.Fatal("config contains both Servers and ServerAddr, only use one or the other") @@ -162,8 +183,10 @@ func runClient(configFileName *string) { for _, serverHostPort := range config.Servers { clientServers = append(clientServers, makeServer(serverHostPort)) } + serverListToLog = fmt.Sprintf("[%s]", strings.Join(config.Servers, ", ")) } else { clientServers = []ClientServer{makeServer(config.ServerAddr)} + serverListToLog = config.ServerAddr } if config.ServiceToLocalAddrMap != nil { @@ -325,10 +348,29 @@ func runClient(configFileName *string) { go server.Client.Start() } - log.Print("runClient(): the client should be running now\n") + log.Printf( + "runClient(): the threshold client should be running now 🏔️⛰️🛤️⛰️🏔️ \n connecting to %s... \n", + serverListToLog, + ) + + log.Printf( + "runClient(): I am listening on %s for SOCKS5 forward proxy \n", + config.ForwardProxyListenAddress, + ) + + for { + conn, err := forwardProxyListener.Accept() + if err != nil { + log.Printf("Can't accept incoming connection: forwardProxyListener.Accept() returned %s\n", err) + } + + // TODO better way of determining which one to use for forward proxy. + err = clientServers[0].Client.HandleForwardProxy(conn) + if err != nil { + log.Printf("Can't accept incoming connection %s -> %s because %s\n", conn.RemoteAddr, conn.LocalAddr, err) + } + } - blockForever := make(chan int) - <-blockForever } func runClientAdminApi(config ClientConfig) { diff --git a/tunnel-lib/client.go b/tunnel-lib/client.go index 2ed3471..3efaa48 100644 --- a/tunnel-lib/client.go +++ b/tunnel-lib/client.go @@ -591,7 +591,7 @@ func (c *Client) listenForwardProxy(ct *control) error { err := ct.send(proto.ControlMessage{Action: proto.RequestForwardProxy}) if err != nil { - return fmt.Errorf("failure seding control message: %s", err) + return fmt.Errorf("failure sending control message: %s", err) } if c.config.DebugLog { From c2580fcd5aba3a5ad708331ebcef48f36d895688 Mon Sep 17 00:00:00 2001 From: forest Date: Thu, 10 Jun 2021 16:05:50 -0500 Subject: [PATCH 26/36] finishing up first try for SOCKS5 forward proxy support --- go.mod | 3 + go.sum | 11 +++ tunnel-lib/client.go | 63 ++-------------- tunnel-lib/server.go | 141 +++++++++++++++++------------------ tunnel-lib/util.go | 171 +++++++++++++++++++++++++++++++++++++++++++ 5 files changed, 262 insertions(+), 127 deletions(-) diff --git a/go.mod b/go.mod index 99ba466..b5b74ec 100644 --- a/go.mod +++ b/go.mod @@ -3,8 +3,11 @@ module git.sequentialread.com/forest/threshold go 1.14 require ( + git.sequentialread.com/forest/pkg-errors v0.9.2 // indirect github.com/armon/go-proxyproto v0.0.0-20210323213023-7e956b284f0a + github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5 // indirect github.com/cenkalti/backoff v2.1.0+incompatible github.com/gorilla/websocket v1.4.0 github.com/hashicorp/yamux v0.0.0-20181012175058-2f1d1f20f75d + golang.org/x/net v0.0.0-20210610132358-84b48f89b13b // indirect ) diff --git a/go.sum b/go.sum index d239f7a..bd59daf 100644 --- a/go.sum +++ b/go.sum @@ -1,12 +1,23 @@ +git.sequentialread.com/forest/pkg-errors v0.9.2 h1:j6pwbL6E+TmE7TD0tqRtGwuoCbCfO6ZR26Nv5nest9g= +git.sequentialread.com/forest/pkg-errors v0.9.2/go.mod h1:8TkJ/f8xLWFIAid20aoqgDZcCj9QQt+FU+rk415XO1w= git.sequentialread.com/forest/tunnel v0.0.0-20170601195443-35a8b95662bf h1:2flo/nnhfe3sSxQ/MHlK7KoY54tQ1pAvMzkh0ZOxyH4= git.sequentialread.com/forest/tunnel v0.0.0-20170601195443-35a8b95662bf/go.mod h1:i+PvDDsWjggoCQOO8bGJJKRB9qfxmHk5yzIEA/h8dzg= github.com/armon/go-proxyproto v0.0.0-20180202201750-5b7edb60ff5f h1:SaJ6yqg936TshyeFZqQE+N+9hYkIeL9AMr7S4voCl10= github.com/armon/go-proxyproto v0.0.0-20180202201750-5b7edb60ff5f/go.mod h1:QmP9hvJ91BbJmGVGSbutW19IC0Q9phDCLGaomwTJbgU= github.com/armon/go-proxyproto v0.0.0-20210323213023-7e956b284f0a h1:AP/vsCIvJZ129pdm9Ek7bH7yutN3hByqsMoNrWAxRQc= github.com/armon/go-proxyproto v0.0.0-20210323213023-7e956b284f0a/go.mod h1:QmP9hvJ91BbJmGVGSbutW19IC0Q9phDCLGaomwTJbgU= +github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5 h1:0CwZNZbxp69SHPdPJAN/hZIm0C4OItdklCFmMRWYpio= +github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5/go.mod h1:wHh0iHkYZB8zMSxRWpUBQtwG5a7fFgvEO+odwuTv2gs= github.com/cenkalti/backoff v2.1.0+incompatible h1:FIRvWBZrzS4YC7NT5cOuZjexzFvIr+Dbi6aD1cZaNBk= github.com/cenkalti/backoff v2.1.0+incompatible/go.mod h1:90ReRw6GdpyfrHakVjL/QHaoyV4aDUVVkXQJJJ3NXXM= github.com/gorilla/websocket v1.4.0 h1:WDFjx/TMzVgy9VdMMQi2K2Emtwi2QcUQsztZ/zLaH/Q= github.com/gorilla/websocket v1.4.0/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ= github.com/hashicorp/yamux v0.0.0-20181012175058-2f1d1f20f75d h1:kJCB4vdITiW1eC1vq2e6IsrXKrZit1bv/TDYFGMp4BQ= github.com/hashicorp/yamux v0.0.0-20181012175058-2f1d1f20f75d/go.mod h1:+NfK9FKeTrX5uv1uIXGdwYDTeHna2qgaIlx54MXqjAM= +golang.org/x/net v0.0.0-20210610132358-84b48f89b13b h1:k+E048sYJHyVnsr1GDrRZWQ32D2C7lWs9JRc0bel53A= +golang.org/x/net v0.0.0-20210610132358-84b48f89b13b/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= diff --git a/tunnel-lib/client.go b/tunnel-lib/client.go index 3efaa48..c58ddd5 100644 --- a/tunnel-lib/client.go +++ b/tunnel-lib/client.go @@ -549,9 +549,15 @@ func (c *Client) listenControl(ct *control) error { if c.config.DebugLog { log.Printf("Client.connect(): Received control msg %+v\n", msg) - log.Println("Client.connect(): Opening a new stream from server session") } + if msg.Action != proto.RequestClientSession { + return fmt.Errorf("control message from server had action = %d, expected %d", msg.Action, proto.RequestClientSession) + } + + if c.config.DebugLog { + log.Println("Client.connect(): Opening a new stream from server session") + } remote, err := c.session.Open() if err != nil { return err @@ -608,62 +614,9 @@ func (c *Client) listenForwardProxy(ct *control) error { } go func() { - BlockingBidirectionalPipe(conn, remoteConn, "from client", "to SOCKS server", strconv.Itoa(forwardProxyConnectionId), c.config.DebugLog) + blockingBidirectionalPipe(conn, remoteConn, "from client", "to SOCKS server", strconv.Itoa(forwardProxyConnectionId), c.config.DebugLog) conn.Close() remoteConn.Close() }() } } - -func BlockingBidirectionalPipe(conn1, conn2 net.Conn, name1, name2 string, connectionId string, debugLog bool) { - chanFromConn := func(conn net.Conn, name, connectionId string) chan []byte { - c := make(chan []byte) - - go func() { - b := make([]byte, 1024) - - for { - n, err := conn.Read(b) - if n > 0 { - res := make([]byte, n) - // Copy the buffer so it doesn't get changed while read by the recipient. - copy(res, b[:n]) - c <- res - } - if err != nil { - log.Printf("%s %s read error %s\n", connectionId, name, err) - c <- nil - break - } - } - }() - - return c - } - - chan1 := chanFromConn(conn1, fmt.Sprint(name1, "->", name2), connectionId) - chan2 := chanFromConn(conn2, fmt.Sprint(name2, "->", name1), connectionId) - - for { - select { - case b1 := <-chan1: - if b1 == nil { - if debugLog { - log.Printf("connection %s %s EOF\n", connectionId, name1) - } - return - } else { - conn2.Write(b1) - } - case b2 := <-chan2: - if b2 == nil { - if debugLog { - log.Printf("connection %s %s EOF\n", connectionId, name2) - } - return - } else { - conn1.Write(b2) - } - } - } -} diff --git a/tunnel-lib/server.go b/tunnel-lib/server.go index 96f9526..59b05dc 100644 --- a/tunnel-lib/server.go +++ b/tunnel-lib/server.go @@ -4,7 +4,6 @@ package tunnel import ( - "errors" "fmt" "io" "log" @@ -16,8 +15,10 @@ import ( "sync" "time" + errors "git.sequentialread.com/forest/pkg-errors" "git.sequentialread.com/forest/threshold/tunnel-lib/proto" + "github.com/armon/go-socks5" "github.com/hashicorp/yamux" ) @@ -41,6 +42,8 @@ type Server struct { // sessionsMu protects sessions. sessionsMu sync.Mutex + socks5Server *socks5.Server + // controls contains the control connection from the client to the server. controls *controls @@ -142,9 +145,16 @@ func NewServer(cfg *ServerConfig) (*Server, error) { connCh: connCh, } + socks5Server, err := socks5.New(&socks5.Config{}) + + if err != nil { + return nil, errors.Wrap(err, "could not create new socks5 server") + } + s := &Server{ pending: make(map[string]chan net.Conn), sessions: make(map[string]*yamux.Session), + socks5Server: socks5Server, onConnectCallbacks: newCallbacks("OnConnect"), onDisconnectCallbacks: newCallbacks("OnDisconnect"), virtualAddrs: newVirtualAddrs(opts), @@ -253,17 +263,19 @@ func (s *Server) handleTCPConn(conn net.Conn) error { disconnectedChan := make(chan bool) + // We don't include remote address or service info here + // because the server should only collect the minimum required amount of metric data + // -- the client can collect more detailed metrics if they want. + inboundMetric := BandwidthMetric{ - Service: listenerInfo.BackendService, - ClientId: listenerInfo.AssociatedClientId, - RemoteAddress: conn.RemoteAddr(), - Inbound: true, + Service: listenerInfo.BackendService, + ClientId: listenerInfo.AssociatedClientId, + Inbound: true, } outboundMetric := BandwidthMetric{ - Service: listenerInfo.BackendService, - ClientId: listenerInfo.AssociatedClientId, - RemoteAddress: conn.RemoteAddr(), - Inbound: false, + Service: listenerInfo.BackendService, + ClientId: listenerInfo.AssociatedClientId, + Inbound: false, } go s.proxy(disconnectedChan, conn, stream, outboundMetric, s.bandwidth, "outbound from tunnel to remote client") @@ -295,65 +307,6 @@ func (s *Server) proxy(disconnectedChan chan bool, dst, src net.Conn, metric Ban } } -// copied from the go standard library source code (io.Copy) with metric collection added. -func ioCopyWithMetrics(dst io.Writer, src io.Reader, metric BandwidthMetric, bandwidth chan<- BandwidthMetric) (written int64, err error) { - size := 32 * 1024 - if l, ok := src.(*io.LimitedReader); ok && int64(size) > l.N { - if l.N < 1 { - size = 1 - } else { - size = int(l.N) - } - } - chunkForMetrics := 0 - buf := make([]byte, size) - - for { - nr, er := src.Read(buf) - if nr > 0 { - nw, ew := dst.Write(buf[0:nr]) - if nw > 0 { - chunkForMetrics += nw - if chunkForMetrics >= metricChunkSize { - bandwidth <- BandwidthMetric{ - Inbound: metric.Inbound, - Service: metric.Service, - ClientId: metric.ClientId, - RemoteAddress: metric.RemoteAddress, - Bytes: chunkForMetrics, - } - chunkForMetrics = 0 - } - written += int64(nw) - } - if ew != nil { - err = ew - break - } - if nr != nw { - err = io.ErrShortWrite - break - } - } - if er != nil { - if er != io.EOF { - err = er - } - break - } - } - if chunkForMetrics > 0 { - bandwidth <- BandwidthMetric{ - Inbound: metric.Inbound, - Service: metric.Service, - ClientId: metric.ClientId, - RemoteAddress: metric.RemoteAddress, - Bytes: chunkForMetrics, - } - } - return written, err -} - func (s *Server) dial(identifier string, service string) (net.Conn, error) { control, ok := s.getControl(identifier) if !ok { @@ -515,12 +468,19 @@ func (s *Server) controlHandler(w http.ResponseWriter, r *http.Request) (ctErr e func (s *Server) listenControl(ct *control) { s.onConnect(ct.identifier) + connectionId := 0 for { - var msg map[string]interface{} + + connectionId++ + + var msg proto.ControlMessage err := ct.dec.Decode(&msg) if err != nil { if s.debugLog { - log.Printf("Server.listenControl(): Closing client connection: '%s'\n", ct.identifier) + log.Printf( + "Server.listenControl(): connectionId: %d: Closing connection for client: '%s'\n", + connectionId, ct.identifier, + ) } // close client connection so it reconnects again @@ -533,7 +493,7 @@ func (s *Server) listenControl(ct *control) { s.onDisconnect(ct.identifier, err) if err != io.EOF { - log.Printf("Server.listenControl(): decode err: %s\n", err) + log.Printf("Server.listenControl(): connectionId: %d decode err: %s\n", connectionId, err) } return } @@ -542,7 +502,44 @@ func (s *Server) listenControl(ct *control) { // underlying connection needs to establihsed, we know when we have // disconnection(above), so we can cleanup the connection. if s.debugLog { - log.Printf("Server.listenControl(): msg: %s\n", msg) + log.Printf("Server.listenControl(): connectionId: %d msg: %s\n", connectionId, msg) + } + + if msg.Action == proto.RequestForwardProxy { + session, err := s.getSession(ct.identifier) + if err != nil { + fmt.Printf( + "failed to accept RequestForwardProxy from client '%s' connectionId: %d: getSession() returned %s\n", + connectionId, ct.identifier, err, + ) + } + remote, err := session.Open() + if err != nil { + fmt.Printf( + "failed to accept RequestForwardProxy from client '%s' connectionId: %d: session.Open() returned %s\n", + connectionId, ct.identifier, err, + ) + } + + go func(connectionId int) { + defer remote.Close() + metricsWrappedConn := ConnWithMetrics{ + underlying: remote, + metricsChannel: s.bandwidth, + inbound: false, + clientId: ct.identifier, + } + err := s.socks5Server.ServeConn(metricsWrappedConn) + if err != nil { + fmt.Printf( + "error in RequestForwardProxy from client '%s' connectionId: %d: socks5Server.ServeConn() failed with %s\n", + ct.identifier, connectionId, err, + ) + } + }(connectionId) + + } else { + fmt.Printf("control message from client had action = %d, expected %d\n", msg.Action, proto.RequestForwardProxy) } } } diff --git a/tunnel-lib/util.go b/tunnel-lib/util.go index 40f0e78..47d690e 100644 --- a/tunnel-lib/util.go +++ b/tunnel-lib/util.go @@ -3,6 +3,8 @@ package tunnel import ( "crypto/tls" "fmt" + "io" + "log" "net" "sync" "time" @@ -119,3 +121,172 @@ func scheme(conn net.Conn) (scheme string) { return } + +func blockingBidirectionalPipe(conn1, conn2 net.Conn, name1, name2 string, connectionId string, debugLog bool) { + chanFromConn := func(conn net.Conn, name, connectionId string) chan []byte { + c := make(chan []byte) + + go func() { + b := make([]byte, 1024) + + for { + n, err := conn.Read(b) + if n > 0 { + res := make([]byte, n) + // Copy the buffer so it doesn't get changed while read by the recipient. + copy(res, b[:n]) + c <- res + } + if err != nil { + log.Printf("%s %s read error %s\n", connectionId, name, err) + c <- nil + break + } + } + }() + + return c + } + + chan1 := chanFromConn(conn1, fmt.Sprint(name1, "->", name2), connectionId) + chan2 := chanFromConn(conn2, fmt.Sprint(name2, "->", name1), connectionId) + + for { + select { + case b1 := <-chan1: + if b1 == nil { + if debugLog { + log.Printf("connection %s %s EOF\n", connectionId, name1) + } + return + } else { + conn2.Write(b1) + } + case b2 := <-chan2: + if b2 == nil { + if debugLog { + log.Printf("connection %s %s EOF\n", connectionId, name2) + } + return + } else { + conn1.Write(b2) + } + } + } +} + +// copied from the go standard library source code (io.Copy) with metric collection added. +func ioCopyWithMetrics(dst io.Writer, src io.Reader, metric BandwidthMetric, bandwidth chan<- BandwidthMetric) (written int64, err error) { + size := 32 * 1024 + if l, ok := src.(*io.LimitedReader); ok && int64(size) > l.N { + if l.N < 1 { + size = 1 + } else { + size = int(l.N) + } + } + chunkForMetrics := 0 + buf := make([]byte, size) + + for { + nr, er := src.Read(buf) + if nr > 0 { + nw, ew := dst.Write(buf[0:nr]) + if nw > 0 { + chunkForMetrics += nw + if chunkForMetrics >= metricChunkSize { + bandwidth <- BandwidthMetric{ + Inbound: metric.Inbound, + Service: metric.Service, + ClientId: metric.ClientId, + RemoteAddress: metric.RemoteAddress, + Bytes: chunkForMetrics, + } + chunkForMetrics = 0 + } + written += int64(nw) + } + if ew != nil { + err = ew + break + } + if nr != nw { + err = io.ErrShortWrite + break + } + } + if er != nil { + if er != io.EOF { + err = er + } + break + } + } + if chunkForMetrics > 0 { + bandwidth <- BandwidthMetric{ + Inbound: metric.Inbound, + Service: metric.Service, + ClientId: metric.ClientId, + RemoteAddress: metric.RemoteAddress, + Bytes: chunkForMetrics, + } + } + return written, err +} + +type ConnWithMetrics struct { + underlying net.Conn + metricsChannel chan<- BandwidthMetric + inbound bool + service string + clientId string + remoteAddress net.Addr +} + +func (conn ConnWithMetrics) Read(b []byte) (n int, err error) { + n, err = conn.underlying.Read(b) + conn.metricsChannel <- BandwidthMetric{ + Inbound: conn.inbound, + ClientId: conn.clientId, + RemoteAddress: conn.remoteAddress, + Service: conn.service, + Bytes: n, + } + return n, err +} + +func (conn ConnWithMetrics) Write(b []byte) (n int, err error) { + n, err = conn.underlying.Write(b) + conn.metricsChannel <- BandwidthMetric{ + Inbound: !conn.inbound, + ClientId: conn.clientId, + RemoteAddress: conn.remoteAddress, + Service: conn.service, + Bytes: n, + } + return n, err +} + +func (conn ConnWithMetrics) Close() error { + return conn.underlying.Close() +} + +func (conn ConnWithMetrics) LocalAddr() net.Addr { + return conn.underlying.LocalAddr() +} + +func (conn ConnWithMetrics) RemoteAddr() net.Addr { + return conn.underlying.RemoteAddr() +} + +func (conn ConnWithMetrics) SetDeadline(t time.Time) error { + return conn.underlying.SetDeadline(t) +} + +func (conn ConnWithMetrics) SetReadDeadline(t time.Time) error { + return conn.underlying.SetReadDeadline(t) +} + +func (conn ConnWithMetrics) SetWriteDeadline(t time.Time) error { + return conn.underlying.SetWriteDeadline(t) +} From b5607fc0931074aa84707cc92569ccb47150b4ab Mon Sep 17 00:00:00 2001 From: forest Date: Thu, 1 Jul 2021 15:32:32 -0500 Subject: [PATCH 27/36] move module correctly --- go.sum | 4 ++-- tunnel-lib/README.md | 6 +++--- tunnel-lib/helper_test.go | 4 ++-- tunnel-lib/tunnel_test.go | 4 ++-- tunnel-lib/tunneltest/state_recorder.go | 2 +- tunnel-lib/tunneltest/tunneltest.go | 2 +- tunnel-lib/websocket_test.go | 2 +- 7 files changed, 12 insertions(+), 12 deletions(-) diff --git a/go.sum b/go.sum index d239f7a..1ff7471 100644 --- a/go.sum +++ b/go.sum @@ -1,5 +1,5 @@ -git.sequentialread.com/forest/tunnel v0.0.0-20170601195443-35a8b95662bf h1:2flo/nnhfe3sSxQ/MHlK7KoY54tQ1pAvMzkh0ZOxyH4= -git.sequentialread.com/forest/tunnel v0.0.0-20170601195443-35a8b95662bf/go.mod h1:i+PvDDsWjggoCQOO8bGJJKRB9qfxmHk5yzIEA/h8dzg= +git.sequentialread.com/forest/threshold v0.0.0-20170601195443-35a8b95662bf h1:2flo/nnhfe3sSxQ/MHlK7KoY54tQ1pAvMzkh0ZOxyH4= +git.sequentialread.com/forest/threshold v0.0.0-20170601195443-35a8b95662bf/go.mod h1:i+PvDDsWjggoCQOO8bGJJKRB9qfxmHk5yzIEA/h8dzg= github.com/armon/go-proxyproto v0.0.0-20180202201750-5b7edb60ff5f h1:SaJ6yqg936TshyeFZqQE+N+9hYkIeL9AMr7S4voCl10= github.com/armon/go-proxyproto v0.0.0-20180202201750-5b7edb60ff5f/go.mod h1:QmP9hvJ91BbJmGVGSbutW19IC0Q9phDCLGaomwTJbgU= github.com/armon/go-proxyproto v0.0.0-20210323213023-7e956b284f0a h1:AP/vsCIvJZ129pdm9Ek7bH7yutN3hByqsMoNrWAxRQc= diff --git a/tunnel-lib/README.md b/tunnel-lib/README.md index b68f7c1..b72f708 100644 --- a/tunnel-lib/README.md +++ b/tunnel-lib/README.md @@ -28,7 +28,7 @@ package main import ( "net/http" - "git.sequentialread.com/forest/tunnel" + "git.sequentialread.com/forest/threshold" ) func main() { @@ -48,7 +48,7 @@ Let us now create the client side part: ```go package main -import "git.sequentialread.com/forest/tunnel" +import "git.sequentialread.com/forest/threshold" func main() { cfg := &tunnel.ClientConfig{ @@ -77,7 +77,7 @@ That's it. There are many options that can be changed, such as a static local address for your client. Have alook at the -[documentation](http://godoc.org/git.sequentialread.com/forest/tunnel) +[documentation](http://godoc.org/git.sequentialread.com/forest/threshold) # Protocol diff --git a/tunnel-lib/helper_test.go b/tunnel-lib/helper_test.go index 7564e1b..f968147 100644 --- a/tunnel-lib/helper_test.go +++ b/tunnel-lib/helper_test.go @@ -14,8 +14,8 @@ import ( "os" "time" - tunnel "git.sequentialread.com/forest/tunnel/tunnel-lib" - "git.sequentialread.com/forest/tunnel/tunnel-lib/tunneltest" + tunnel "git.sequentialread.com/forest/threshold/tunnel-lib" + "git.sequentialread.com/forest/threshold/tunnel-lib/tunneltest" "github.com/gorilla/websocket" ) diff --git a/tunnel-lib/tunnel_test.go b/tunnel-lib/tunnel_test.go index e3f7d5b..0023894 100644 --- a/tunnel-lib/tunnel_test.go +++ b/tunnel-lib/tunnel_test.go @@ -7,8 +7,8 @@ import ( "testing" "time" - tunnel "git.sequentialread.com/forest/tunnel/tunnel-lib" - "git.sequentialread.com/forest/tunnel/tunnel-lib/tunneltest" + tunnel "git.sequentialread.com/forest/threshold/tunnel-lib" + "git.sequentialread.com/forest/threshold/tunnel-lib/tunneltest" "github.com/cenkalti/backoff" ) diff --git a/tunnel-lib/tunneltest/state_recorder.go b/tunnel-lib/tunneltest/state_recorder.go index 851dbe3..1d13ed7 100644 --- a/tunnel-lib/tunneltest/state_recorder.go +++ b/tunnel-lib/tunneltest/state_recorder.go @@ -6,7 +6,7 @@ import ( "sync" "time" - tunnel "git.sequentialread.com/forest/tunnel/tunnel-lib" + tunnel "git.sequentialread.com/forest/threshold/tunnel-lib" ) var ( diff --git a/tunnel-lib/tunneltest/tunneltest.go b/tunnel-lib/tunneltest/tunneltest.go index 333da5b..98c8d6b 100644 --- a/tunnel-lib/tunneltest/tunneltest.go +++ b/tunnel-lib/tunneltest/tunneltest.go @@ -14,7 +14,7 @@ import ( "testing" "time" - tunnel "git.sequentialread.com/forest/tunnel/tunnel-lib" + tunnel "git.sequentialread.com/forest/threshold/tunnel-lib" ) var debugNet = os.Getenv("DEBUGNET") == "1" diff --git a/tunnel-lib/websocket_test.go b/tunnel-lib/websocket_test.go index a6f8de1..35c2726 100644 --- a/tunnel-lib/websocket_test.go +++ b/tunnel-lib/websocket_test.go @@ -6,7 +6,7 @@ import ( "reflect" "testing" - "git.sequentialread.com/forest/tunnel/tunnel-lib/tunneltest" + "git.sequentialread.com/forest/threshold/tunnel-lib/tunneltest" ) func testWebsocket(name string, n int, t *testing.T, tt *tunneltest.TunnelTest) { From 1a2c3fd9dd64e11ba742b3623a1cdb05dc8afebd Mon Sep 17 00:00:00 2001 From: forest Date: Thu, 1 Jul 2021 15:48:49 -0500 Subject: [PATCH 28/36] support local SOCKS5 proxy for threshold clients --- go.mod | 1 + go.sum | 7 +++++++ main_client.go | 23 ++++++++++++++++++++++- 3 files changed, 30 insertions(+), 1 deletion(-) diff --git a/go.mod b/go.mod index 99ba466..1e7996b 100644 --- a/go.mod +++ b/go.mod @@ -7,4 +7,5 @@ require ( github.com/cenkalti/backoff v2.1.0+incompatible github.com/gorilla/websocket v1.4.0 github.com/hashicorp/yamux v0.0.0-20181012175058-2f1d1f20f75d + golang.org/x/net v0.0.0-20210614182718-04defd469f4e // indirect ) diff --git a/go.sum b/go.sum index 1ff7471..b6e598a 100644 --- a/go.sum +++ b/go.sum @@ -10,3 +10,10 @@ github.com/gorilla/websocket v1.4.0 h1:WDFjx/TMzVgy9VdMMQi2K2Emtwi2QcUQsztZ/zLaH github.com/gorilla/websocket v1.4.0/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ= github.com/hashicorp/yamux v0.0.0-20181012175058-2f1d1f20f75d h1:kJCB4vdITiW1eC1vq2e6IsrXKrZit1bv/TDYFGMp4BQ= github.com/hashicorp/yamux v0.0.0-20181012175058-2f1d1f20f75d/go.mod h1:+NfK9FKeTrX5uv1uIXGdwYDTeHna2qgaIlx54MXqjAM= +golang.org/x/net v0.0.0-20210614182718-04defd469f4e h1:XpT3nA5TvE525Ne3hInMh6+GETgn27Zfm9dxsThnX2Q= +golang.org/x/net v0.0.0-20210614182718-04defd469f4e/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= diff --git a/main_client.go b/main_client.go index b2b45e4..fe025ef 100644 --- a/main_client.go +++ b/main_client.go @@ -25,6 +25,7 @@ import ( tunnel "git.sequentialread.com/forest/threshold/tunnel-lib" "git.sequentialread.com/forest/threshold/tunnel-lib/proto" proxyprotocol "github.com/armon/go-proxyproto" + "golang.org/x/net/proxy" ) type ClientConfig struct { @@ -42,6 +43,7 @@ type ClientConfig struct { CaCertificate string ClientTlsKey string ClientTlsCertificate string + LocalSOCKS5Address string // use this when a local proxy is required to talk to the threshold server. AdminUnixSocket string AdminAPIPort int AdminAPICACertificateFile string @@ -186,6 +188,14 @@ func runClient(configFileName *string) { dialFunction := net.Dial + if config.LocalSOCKS5Address != "" { + dialer, err := proxy.SOCKS5("tcp", "PROXY_IP", nil, proxy.Direct) + if err != nil { + log.Fatal("can't connect to the proxy:", err) + } + dialFunction = dialer.Dial + } + var cert tls.Certificate hasFiles := config.ClientTlsCertificateFile != "" && config.ClientTlsKeyFile != "" hasLiterals := config.ClientTlsCertificate != "" && config.ClientTlsKey != "" @@ -269,8 +279,19 @@ func runClient(configFileName *string) { } tlsClientConfig.BuildNameToCertificate() + // wrap whatever dial function we have right now with TLS. + existingDialFunction := dialFunction dialFunction = func(network, address string) (net.Conn, error) { - return tls.Dial(network, address, tlsClientConfig) + conn, err := existingDialFunction(network, address) + if err != nil { + return nil, err + } + tlsConn := tls.Client(conn, tlsClientConfig) + err = tlsConn.Handshake() + if err != nil { + return nil, err + } + return tlsConn, nil } go runClientAdminApi(config) From 7816c9d1379e3b3b2a9836f8e2ef1a83523041d9 Mon Sep 17 00:00:00 2001 From: forest Date: Thu, 1 Jul 2021 22:19:18 -0500 Subject: [PATCH 29/36] finish implementing LocalSOCKS5Address and fix a couple bugs --- README.md | 1 + build.sh | 4 +- go.mod | 1 + go.sum | 2 + main_client.go | 286 ++++++++++++++++++++++++++++---------- main_server.go | 2 +- tunnel-lib/virtualaddr.go | 3 +- 7 files changed, 219 insertions(+), 80 deletions(-) diff --git a/README.md b/README.md index 976468b..26e53bf 100644 --- a/README.md +++ b/README.md @@ -28,6 +28,7 @@ To edit it, download the diagram file %[1]v\n", ipBytes) + } + } + } + + return toReturn, nil +} diff --git a/main_server.go b/main_server.go index 9b9ff98..c8f2518 100644 --- a/main_server.go +++ b/main_server.go @@ -361,7 +361,7 @@ func setListeners(tenantId string, listenerConfigs []ListenerConfig) (int, strin if err != nil { if strings.Contains(err.Error(), "already in use") { - return http.StatusConflict, fmt.Sprintf("Port Conflict: Port %s is reserved or already in use", listenAddress) + return http.StatusConflict, fmt.Sprintf("Port Conflict: Port %s:%d is reserved or already in use", listenAddress, newListenerConfig.ListenPort) } log.Printf("setListeners(): can't net.Listen(\"tcp\", \"%s\") because %s \n", listenAddress, err) diff --git a/tunnel-lib/virtualaddr.go b/tunnel-lib/virtualaddr.go index e5dc7f7..ae09a84 100644 --- a/tunnel-lib/virtualaddr.go +++ b/tunnel-lib/virtualaddr.go @@ -208,13 +208,14 @@ func (vaddr *vaddrStorage) Delete(ip net.IP, port int, hostnameGlob string) { func (vaddr *vaddrStorage) newListener(ip net.IP, port int) (*listener, error) { listenAddress := net.JoinHostPort(ip.String(), strconv.Itoa(port)) - fmt.Printf("now listening on %s\n\n", listenAddress) netListener, err := net.Listen("tcp", listenAddress) if err != nil { return nil, err } + fmt.Printf("now listening on %s\n\n", listenAddress) + return &listener{ Listener: netListener, vaddrOptions: vaddr.vaddrOptions, From a3362a19dfd0230161fae907eeee8ae9c955c449 Mon Sep 17 00:00:00 2001 From: forest Date: Fri, 16 Jul 2021 13:37:36 -0500 Subject: [PATCH 30/36] implement maximum reconnect --- main_client.go | 56 +++++++++++++++++++++++++++++++++----------- tunnel-lib/client.go | 4 +++- tunnel-lib/util.go | 2 +- 3 files changed, 46 insertions(+), 16 deletions(-) diff --git a/main_client.go b/main_client.go index 044132f..745f9d5 100644 --- a/main_client.go +++ b/main_client.go @@ -34,20 +34,21 @@ import ( ) type ClientConfig struct { - DebugLog bool - ClientId string - GreenhouseDomain string - GreenhouseAPIToken string - GreenhouseThresholdPort int - ServerAddr string - Servers []string - DefaultTunnels *LiveConfigUpdate - CaCertificateFilesGlob string - ClientTlsKeyFile string - ClientTlsCertificateFile string - CaCertificate string - ClientTlsKey string - ClientTlsCertificate string + DebugLog bool + ClientId string + GreenhouseDomain string + GreenhouseAPIToken string + GreenhouseThresholdPort int + MaximumConnectionRetrySeconds int + ServerAddr string + Servers []string + DefaultTunnels *LiveConfigUpdate + CaCertificateFilesGlob string + ClientTlsKeyFile string + ClientTlsCertificateFile string + CaCertificate string + ClientTlsKey string + ClientTlsCertificate string // use this when a local proxy is required to talk to the threshold server. // if you set the hostname to "gateway", like "LocalSOCKS5Address": "gateway:1080" @@ -77,6 +78,23 @@ type ThresholdTenantInfo struct { ThresholdServers []string } +type maximumBackoff struct { + Maximum time.Duration + Base tunnel.Backoff +} + +func (bo *maximumBackoff) NextBackOff() time.Duration { + result := bo.Base.NextBackOff() + if result > bo.Maximum { + return bo.Maximum + } + return result +} + +func (bo *maximumBackoff) Reset() { + bo.Base.Reset() +} + type clientAdminAPI struct{} // Client State @@ -356,7 +374,16 @@ func runClient(configFileName *string) { } } + maximumConnectionRetrySeconds := 60 + if config.MaximumConnectionRetrySeconds != 0 { + maximumConnectionRetrySeconds = config.MaximumConnectionRetrySeconds + } for _, server := range clientServers { + // make a separate backoff instance for each server. + myBackoff := maximumBackoff{ + Maximum: time.Second * time.Duration(maximumConnectionRetrySeconds), + Base: tunnel.NewExponentialBackoff(), + } clientStateChanges := make(chan *tunnel.ClientStateChange) tunnelClientConfig := &tunnel.ClientConfig{ DebugLog: config.DebugLog, @@ -366,6 +393,7 @@ func runClient(configFileName *string) { Proxy: proxyFunc, Dial: dialFunction, StateChanges: clientStateChanges, + Backoff: &myBackoff, } client, err := tunnel.NewClient(tunnelClientConfig) diff --git a/tunnel-lib/client.go b/tunnel-lib/client.go index 92e9c08..9d44e7b 100644 --- a/tunnel-lib/client.go +++ b/tunnel-lib/client.go @@ -202,9 +202,11 @@ func NewClient(cfg *ClientConfig) (*Client, error) { proxy = (&TCPProxy{FetchLocalAddr: cfg.FetchLocalAddr, DebugLog: cfg.DebugLog}).Proxy } - var bo Backoff = newForeverBackoff() + var bo Backoff if cfg.Backoff != nil { bo = cfg.Backoff + } else { + bo = NewExponentialBackoff() } client := &Client{ diff --git a/tunnel-lib/util.go b/tunnel-lib/util.go index 40f0e78..30ca0c5 100644 --- a/tunnel-lib/util.go +++ b/tunnel-lib/util.go @@ -33,7 +33,7 @@ type expBackoff struct { bk *backoff.ExponentialBackOff } -func newForeverBackoff() *expBackoff { +func NewExponentialBackoff() *expBackoff { eb := &expBackoff{ bk: backoff.NewExponentialBackOff(), } From 54fd606ec240fb6f47a06c6fba025d92280f9d3c Mon Sep 17 00:00:00 2001 From: forest Date: Thu, 22 Jul 2021 12:47:01 -0500 Subject: [PATCH 31/36] fixing go.mod go.sum issues / fixing compile errors in tests --- go.mod | 6 +++--- go.sum | 19 +++++++++++++++++++ main_client.go | 6 +++--- tunnel-lib/tunnel_test.go | 2 +- tunnel-lib/tunneltest/tunneltest.go | 26 +++++++++++++++----------- 5 files changed, 41 insertions(+), 18 deletions(-) diff --git a/go.mod b/go.mod index 0b85f67..0508931 100644 --- a/go.mod +++ b/go.mod @@ -3,11 +3,11 @@ module git.sequentialread.com/forest/threshold go 1.14 require ( - git.sequentialread.com/forest/pkg-errors v0.9.2 // indirect + git.sequentialread.com/forest/pkg-errors v0.9.2 github.com/armon/go-proxyproto v0.0.0-20210323213023-7e956b284f0a - github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5 // indirect + github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5 github.com/cenkalti/backoff v2.1.0+incompatible github.com/gorilla/websocket v1.4.0 github.com/hashicorp/yamux v0.0.0-20181012175058-2f1d1f20f75d - golang.org/x/net v0.0.0-20210614182718-04defd469f4e // indirect + golang.org/x/net v0.0.0-20210614182718-04defd469f4e ) diff --git a/go.sum b/go.sum index e69de29..e8a6102 100644 --- a/go.sum +++ b/go.sum @@ -0,0 +1,19 @@ +git.sequentialread.com/forest/pkg-errors v0.9.2 h1:j6pwbL6E+TmE7TD0tqRtGwuoCbCfO6ZR26Nv5nest9g= +git.sequentialread.com/forest/pkg-errors v0.9.2/go.mod h1:8TkJ/f8xLWFIAid20aoqgDZcCj9QQt+FU+rk415XO1w= +github.com/armon/go-proxyproto v0.0.0-20210323213023-7e956b284f0a h1:AP/vsCIvJZ129pdm9Ek7bH7yutN3hByqsMoNrWAxRQc= +github.com/armon/go-proxyproto v0.0.0-20210323213023-7e956b284f0a/go.mod h1:QmP9hvJ91BbJmGVGSbutW19IC0Q9phDCLGaomwTJbgU= +github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5 h1:0CwZNZbxp69SHPdPJAN/hZIm0C4OItdklCFmMRWYpio= +github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5/go.mod h1:wHh0iHkYZB8zMSxRWpUBQtwG5a7fFgvEO+odwuTv2gs= +github.com/cenkalti/backoff v2.1.0+incompatible h1:FIRvWBZrzS4YC7NT5cOuZjexzFvIr+Dbi6aD1cZaNBk= +github.com/cenkalti/backoff v2.1.0+incompatible/go.mod h1:90ReRw6GdpyfrHakVjL/QHaoyV4aDUVVkXQJJJ3NXXM= +github.com/gorilla/websocket v1.4.0 h1:WDFjx/TMzVgy9VdMMQi2K2Emtwi2QcUQsztZ/zLaH/Q= +github.com/gorilla/websocket v1.4.0/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ= +github.com/hashicorp/yamux v0.0.0-20181012175058-2f1d1f20f75d h1:kJCB4vdITiW1eC1vq2e6IsrXKrZit1bv/TDYFGMp4BQ= +github.com/hashicorp/yamux v0.0.0-20181012175058-2f1d1f20f75d/go.mod h1:+NfK9FKeTrX5uv1uIXGdwYDTeHna2qgaIlx54MXqjAM= +golang.org/x/net v0.0.0-20210614182718-04defd469f4e h1:XpT3nA5TvE525Ne3hInMh6+GETgn27Zfm9dxsThnX2Q= +golang.org/x/net v0.0.0-20210614182718-04defd469f4e/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= diff --git a/main_client.go b/main_client.go index 6d2321b..b1fbe1e 100644 --- a/main_client.go +++ b/main_client.go @@ -130,13 +130,13 @@ func runClient(configFileName *string) { config.GreenhouseThresholdPort = 9056 } if config.TunneledOutboundSOCKS5ListenAddress == "" { - config.TunneledOutboundSOCKS5ListenAddress = "127.0.0.1:8000" + config.TunneledOutboundSOCKS5ListenAddress = "127.0.0.1:1080" } - TunneledOutboundSOCKS5ListenAddress, err := net.ResolveTCPAddr("tcp", config.TunneledOutboundSOCKS5ListenAddress) + tunneledOutboundSOCKS5ListenAddress, err := net.ResolveTCPAddr("tcp", config.TunneledOutboundSOCKS5ListenAddress) if err != nil { log.Fatalf("runClient(): can't net.ResolveTCPAddr(TunneledOutboundSOCKS5ListenAddress) because %s \n", err) } - forwardProxyListener, err := net.ListenTCP("tcp", TunneledOutboundSOCKS5ListenAddress) + forwardProxyListener, err := net.ListenTCP("tcp", tunneledOutboundSOCKS5ListenAddress) if err != nil { log.Fatalf("runClient(): can't net.ListenTCP(\"tcp\", TunneledOutboundSOCKS5ListenAddress) because %s \n", err) } diff --git a/tunnel-lib/tunnel_test.go b/tunnel-lib/tunnel_test.go index 0023894..2f0af6b 100644 --- a/tunnel-lib/tunnel_test.go +++ b/tunnel-lib/tunnel_test.go @@ -177,7 +177,7 @@ func TestNoHost(t *testing.T) { Identifier: "unknown", ServerAddr: tt.ServerAddr().String(), Backoff: noBackoff, - Debug: testing.Verbose(), + DebugLog: true, }) if err != nil { t.Fatalf("client error: %s", err) diff --git a/tunnel-lib/tunneltest/tunneltest.go b/tunnel-lib/tunneltest/tunneltest.go index 98c8d6b..c773576 100644 --- a/tunnel-lib/tunneltest/tunneltest.go +++ b/tunnel-lib/tunneltest/tunneltest.go @@ -185,7 +185,7 @@ func NewTunnelTest() (*TunnelTest, error) { cfg := &tunnel.ServerConfig{ StateChanges: rec.C(), - Debug: testing.Verbose(), + DebugLog: true, } s, err := tunnel.NewServer(cfg) if err != nil { @@ -266,7 +266,7 @@ func (tt *TunnelTest) serveSingle(ident string, t *Tunnel) (bool, error) { l = dbgListener{l} } - localAddr := l.Addr().String() + //localAddr := l.Addr().String() tcpProxy := &tunnel.TCPProxy{FetchLocalAddr: tt.fetchLocalAddr} cfg := &tunnel.ClientConfig{ @@ -274,7 +274,7 @@ func (tt *TunnelTest) serveSingle(ident string, t *Tunnel) (bool, error) { ServerAddr: tt.ServerAddr().String(), Proxy: tcpProxy.Proxy, StateChanges: t.StateChanges, - Debug: testing.Verbose(), + DebugLog: true, } // Register tunnel: @@ -313,6 +313,7 @@ func (tt *TunnelTest) serveSingle(ident string, t *Tunnel) (bool, error) { remote = tt.Listeners[t.RemoteAddrIdent][1] tt.mu.Unlock() } else { + net.ResolveTCPAddr("tcp", t.RemoteAddr) remote, err = net.Listen("tcp", t.RemoteAddr) if err != nil { return false, fmt.Errorf("failed to listen on %q for %q tunnel: %s", t.RemoteAddr, ident, err) @@ -327,7 +328,9 @@ func (tt *TunnelTest) serveSingle(ident string, t *Tunnel) (bool, error) { addrIdent = t.ClientIdent } - tt.Server.AddAddr(remote, t.IP, addrIdent) + // TODO this whole thing needs to be refactored because tt.Server.AddAddr does not accept a listener as an argument any more. + // Used to be like: tt.Server.AddAddr(remote, blahblahblah) + tt.Server.AddAddr(t.IP, 8080, "*", addrIdent, true, t.RemoteAddr) tt.mu.Lock() tt.Listeners[ident] = [2]net.Listener{l, remote} @@ -428,7 +431,7 @@ func (tt *TunnelTest) popServedDeps(tunnels map[string]*Tunnel) error { return nil } -func (tt *TunnelTest) fetchLocalAddr(port int) (string, error) { +func (tt *TunnelTest) fetchLocalAddr(service string) (string, error) { tt.mu.Lock() defer tt.mu.Unlock() @@ -438,17 +441,18 @@ func (tt *TunnelTest) fetchLocalAddr(port int) (string, error) { continue } - _, remotePort, err := parseHostPort(l[1].Addr().String()) - if err != nil { - return "", err - } + remotePort := l[1].Addr().String() + // _, remotePort, err := parseHostPort() + // if err != nil { + // return "", err + // } - if port == remotePort { + if service == remotePort { return l[0].Addr().String(), nil } } - return "", fmt.Errorf("no route for %d port", port) + return "", fmt.Errorf("no route for %s service string", service) } func (tt *TunnelTest) ServerAddr() net.Addr { From 2aa40ea2e9c12e87b759ae5a66f3f14ddfada9f0 Mon Sep 17 00:00:00 2001 From: forest Date: Thu, 22 Jul 2021 16:00:31 -0500 Subject: [PATCH 32/36] fixing ConnWithMetrics, TunneledOutboundSOCKS5 forward proxy appears to be working now --- .gitignore | 1 + main_client.go | 4 +++- main_server.go | 2 +- tunnel-lib/server.go | 4 ++++ tunnel-lib/util.go | 50 ++++++++++++++++++++++++++++++++------------ 5 files changed, 46 insertions(+), 15 deletions(-) diff --git a/.gitignore b/.gitignore index b177d4a..2836b1f 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ build dockerbuild localbuild.sh +config.json \ No newline at end of file diff --git a/main_client.go b/main_client.go index b1fbe1e..83e2989 100644 --- a/main_client.go +++ b/main_client.go @@ -409,7 +409,7 @@ func runClient(configFileName *string) { if config.MaximumConnectionRetrySeconds != 0 { maximumConnectionRetrySeconds = config.MaximumConnectionRetrySeconds } - for _, server := range clientServers { + for i, server := range clientServers { // make a separate backoff instance for each server. myBackoff := maximumBackoff{ Maximum: time.Second * time.Duration(maximumConnectionRetrySeconds), @@ -454,6 +454,7 @@ func runClient(configFileName *string) { })() server.Client = client + clientServers[i] = server go server.Client.Start() } @@ -474,6 +475,7 @@ func runClient(configFileName *string) { } // TODO better way of determining which one to use for forward proxy. + // log.Printf("clientServers: %+v, clientServers[0]: %+v\n", clientServers, clientServers[0]) err = clientServers[0].Client.HandleForwardProxy(conn) if err != nil { log.Printf("Can't accept incoming connection %s -> %s because %s\n", conn.RemoteAddr, conn.LocalAddr, err) diff --git a/main_server.go b/main_server.go index c8f2518..e0312ef 100644 --- a/main_server.go +++ b/main_server.go @@ -115,7 +115,7 @@ func runServer(configFileName *string) { // the Server should only collect metrics when in multi-tenant mode -- this is needed for billing if config.MultiTenantMode { - metricChannel = make(chan tunnel.BandwidthMetric) + metricChannel = make(chan tunnel.BandwidthMetric, 4096) } tunnelServerConfig := &tunnel.ServerConfig{ diff --git a/tunnel-lib/server.go b/tunnel-lib/server.go index 59b05dc..7af67b5 100644 --- a/tunnel-lib/server.go +++ b/tunnel-lib/server.go @@ -506,6 +506,7 @@ func (s *Server) listenControl(ct *control) { } if msg.Action == proto.RequestForwardProxy { + log.Printf("Server.listenControl(): connectionId: %d s.getSession(%s)\n", connectionId, ct.identifier) session, err := s.getSession(ct.identifier) if err != nil { fmt.Printf( @@ -513,6 +514,7 @@ func (s *Server) listenControl(ct *control) { connectionId, ct.identifier, err, ) } + log.Printf("Server.listenControl(): connectionId: %d session.Open()\n", connectionId) remote, err := session.Open() if err != nil { fmt.Printf( @@ -529,6 +531,8 @@ func (s *Server) listenControl(ct *control) { inbound: false, clientId: ct.identifier, } + + log.Printf("Server.listenControl(): connectionId: %d s.socks5Server.ServeConn(metricsWrappedConn)\n", connectionId) err := s.socks5Server.ServeConn(metricsWrappedConn) if err != nil { fmt.Printf( diff --git a/tunnel-lib/util.go b/tunnel-lib/util.go index 00f881c..1078337 100644 --- a/tunnel-lib/util.go +++ b/tunnel-lib/util.go @@ -240,35 +240,59 @@ type ConnWithMetrics struct { inbound bool service string clientId string + inboundBytes int + outboundBytes int remoteAddress net.Addr } func (conn ConnWithMetrics) Read(b []byte) (n int, err error) { n, err = conn.underlying.Read(b) - conn.metricsChannel <- BandwidthMetric{ - Inbound: conn.inbound, - ClientId: conn.clientId, - RemoteAddress: conn.remoteAddress, - Service: conn.service, - Bytes: n, - } + conn.Accumulate(conn.inbound, n) return n, err } func (conn ConnWithMetrics) Write(b []byte) (n int, err error) { n, err = conn.underlying.Write(b) + conn.Accumulate(!conn.inbound, n) + return n, err +} + +func (conn ConnWithMetrics) Close() error { + if conn.inboundBytes > 0 { + conn.PushMetric(true, conn.inboundBytes) + } + if conn.outboundBytes > 0 { + conn.PushMetric(false, conn.outboundBytes) + } + return conn.underlying.Close() +} + +func (conn ConnWithMetrics) Accumulate(inbound bool, n int) { + if inbound { + conn.inboundBytes += n + + if conn.inboundBytes > metricChunkSize { + conn.PushMetric(true, conn.inboundBytes) + conn.inboundBytes = 0 + } + } else { + conn.outboundBytes += n + + if conn.outboundBytes > metricChunkSize { + conn.PushMetric(false, conn.outboundBytes) + conn.outboundBytes = 0 + } + } +} + +func (conn ConnWithMetrics) PushMetric(inbound bool, n int) { conn.metricsChannel <- BandwidthMetric{ - Inbound: !conn.inbound, + Inbound: inbound, ClientId: conn.clientId, RemoteAddress: conn.remoteAddress, Service: conn.service, Bytes: n, } - return n, err -} - -func (conn ConnWithMetrics) Close() error { - return conn.underlying.Close() } func (conn ConnWithMetrics) LocalAddr() net.Addr { From f23d762b8e7a1c3efb6793bbd2562ea792fc434b Mon Sep 17 00:00:00 2001 From: forest Date: Tue, 21 Sep 2021 07:49:26 -0500 Subject: [PATCH 33/36] multiple threshold clients at once & tolerate greenhouse outages --- .gitignore | 3 ++- main_client.go | 54 ++++++++++++++++++++++++++++---------------------- 2 files changed, 32 insertions(+), 25 deletions(-) diff --git a/.gitignore b/.gitignore index 2836b1f..8d64223 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,5 @@ build dockerbuild localbuild.sh -config.json \ No newline at end of file +config.json +threshold \ No newline at end of file diff --git a/main_client.go b/main_client.go index 83e2989..a2bf13b 100644 --- a/main_client.go +++ b/main_client.go @@ -129,16 +129,16 @@ func runClient(configFileName *string) { if config.GreenhouseThresholdPort == 0 { config.GreenhouseThresholdPort = 9056 } - if config.TunneledOutboundSOCKS5ListenAddress == "" { - config.TunneledOutboundSOCKS5ListenAddress = "127.0.0.1:1080" - } - tunneledOutboundSOCKS5ListenAddress, err := net.ResolveTCPAddr("tcp", config.TunneledOutboundSOCKS5ListenAddress) - if err != nil { - log.Fatalf("runClient(): can't net.ResolveTCPAddr(TunneledOutboundSOCKS5ListenAddress) because %s \n", err) - } - forwardProxyListener, err := net.ListenTCP("tcp", tunneledOutboundSOCKS5ListenAddress) - if err != nil { - log.Fatalf("runClient(): can't net.ListenTCP(\"tcp\", TunneledOutboundSOCKS5ListenAddress) because %s \n", err) + var forwardProxyListener *net.TCPListener + if config.TunneledOutboundSOCKS5ListenAddress != "" { + tunneledOutboundSOCKS5ListenAddress, err := net.ResolveTCPAddr("tcp", config.TunneledOutboundSOCKS5ListenAddress) + if err != nil { + log.Fatalf("runClient(): can't net.ResolveTCPAddr(TunneledOutboundSOCKS5ListenAddress) because %s \n", err) + } + forwardProxyListener, err = net.ListenTCP("tcp", tunneledOutboundSOCKS5ListenAddress) + if err != nil { + log.Fatalf("runClient(): can't net.ListenTCP(\"tcp\", TunneledOutboundSOCKS5ListenAddress) because %s \n", err) + } } clientServers = []ClientServer{} @@ -180,12 +180,14 @@ func runClient(configFileName *string) { if err != nil || response.StatusCode != 200 { if err == nil { if response.StatusCode == 401 { - log.Fatalf("bad or expired GreenhouseAPIToken, recieved HTTP 401 Unauthorized from Greenhouse server %s", greenhouseURL) + log.Printf("bad or expired GreenhouseAPIToken, recieved HTTP 401 Unauthorized from Greenhouse server %s", greenhouseURL) } else { - log.Fatalf("server error: recieved HTTP %d from Greenhouse server %s", response.StatusCode, greenhouseURL) + log.Printf("recieved HTTP %d from Greenhouse server %s", response.StatusCode, greenhouseURL) } + } else { + log.Printf("Greenhouse server %s could not be reached: %s", greenhouseURL, err) } - log.Printf("can't reach %s, falling back to DNS lookup...\n", greenhouseURL) + log.Printf("falling back to DNS lookup...\n", greenhouseURL) ips, err := net.LookupIP(config.GreenhouseDomain) if err != nil { log.Fatalf("Failed to lookup GreenhouseDomain '%s'", config.GreenhouseDomain) @@ -468,20 +470,24 @@ func runClient(configFileName *string) { config.TunneledOutboundSOCKS5ListenAddress, ) - for { - conn, err := forwardProxyListener.Accept() - if err != nil { - log.Printf("Can't accept incoming connection: forwardProxyListener.Accept() returned %s\n", err) - } + if forwardProxyListener != nil { + for { + conn, err := forwardProxyListener.Accept() + if err != nil { + log.Printf("Can't accept incoming connection: forwardProxyListener.Accept() returned %s\n", err) + } - // TODO better way of determining which one to use for forward proxy. - // log.Printf("clientServers: %+v, clientServers[0]: %+v\n", clientServers, clientServers[0]) - err = clientServers[0].Client.HandleForwardProxy(conn) - if err != nil { - log.Printf("Can't accept incoming connection %s -> %s because %s\n", conn.RemoteAddr, conn.LocalAddr, err) + // TODO better way of determining which one to use for forward proxy. + // log.Printf("clientServers: %+v, clientServers[0]: %+v\n", clientServers, clientServers[0]) + err = clientServers[0].Client.HandleForwardProxy(conn) + if err != nil { + log.Printf("Can't accept incoming connection %s -> %s because %s\n", conn.RemoteAddr, conn.LocalAddr, err) + } } + } else { + waitForever := make(chan bool) + <-waitForever } - } func runClientAdminApi(config ClientConfig) { From 72dacc7757be8eecc39310a256755229f36f827f Mon Sep 17 00:00:00 2001 From: forest Date: Tue, 21 Sep 2021 12:15:07 -0500 Subject: [PATCH 34/36] fixing log --- main_client.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/main_client.go b/main_client.go index a2bf13b..579d1ae 100644 --- a/main_client.go +++ b/main_client.go @@ -187,7 +187,7 @@ func runClient(configFileName *string) { } else { log.Printf("Greenhouse server %s could not be reached: %s", greenhouseURL, err) } - log.Printf("falling back to DNS lookup...\n", greenhouseURL) + log.Printf("falling back to DNS lookup on '%s'...\n", greenhouseURL) ips, err := net.LookupIP(config.GreenhouseDomain) if err != nil { log.Fatalf("Failed to lookup GreenhouseDomain '%s'", config.GreenhouseDomain) From e215ed157c347b658790ae8b3ebf88445874e528 Mon Sep 17 00:00:00 2001 From: forest Date: Fri, 24 Sep 2021 17:39:43 -0500 Subject: [PATCH 35/36] fixing blatantly wrong port bug and debugging changes --- main_client.go | 41 ++++++++++++++++++++++++++++++++++++----- 1 file changed, 36 insertions(+), 5 deletions(-) diff --git a/main_client.go b/main_client.go index 579d1ae..e4550bf 100644 --- a/main_client.go +++ b/main_client.go @@ -188,6 +188,8 @@ func runClient(configFileName *string) { log.Printf("Greenhouse server %s could not be reached: %s", greenhouseURL, err) } log.Printf("falling back to DNS lookup on '%s'...\n", greenhouseURL) + + // TODO for _, tunnel := range config.DefaultTunnels ips, err := net.LookupIP(config.GreenhouseDomain) if err != nil { log.Fatalf("Failed to lookup GreenhouseDomain '%s'", config.GreenhouseDomain) @@ -209,6 +211,8 @@ func runClient(configFileName *string) { } for _, serverHostPort := range tenantInfo.ThresholdServers { + ip := strings.Split(serverHostPort, ":")[0] + serverHostPort = fmt.Sprintf("%s:%d", ip, config.GreenhouseThresholdPort) clientServers = append(clientServers, makeServer(serverHostPort)) hostPortStringsToLog = append(hostPortStringsToLog, serverHostPort) } @@ -371,6 +375,32 @@ func runClient(configFileName *string) { } addressSplit := strings.Split(address, ":") + + // log.Printf("ASD!! LEN: %d\n", len(tlsClientConfig.Certificates)) + // if len(tlsClientConfig.Certificates) > 0 { + // for i, cert := range tlsClientConfig.Certificates { + + // log.Printf("cert[%d]\n", i) + + // if cert.Leaf != nil { + // bytez := pem.EncodeToMemory(&pem.Block{ + // Bytes: cert.Leaf.Raw, + // Type: "CERTIFICATE", + // }) + // log.Printf("cert[%d].Leaf.Raw:\n%s\n\n", i, bytez) + // } + // if cert.Certificate != nil { + // for j, bytez := range cert.Certificate { + // bytez2 := pem.EncodeToMemory(&pem.Block{ + // Bytes: bytez, + // Type: "CERTIFICATE", + // }) + // log.Printf("cert[%d][%d].Raw:\n%s\n\n", i, j, bytez2) + // } + // } + // } + // } + tlsConn := tls.Client(conn, &tls.Config{ ServerName: addressSplit[0], Certificates: tlsClientConfig.Certificates, @@ -378,6 +408,7 @@ func runClient(configFileName *string) { }) err = tlsConn.Handshake() if err != nil { + log.Printf("tlsConn.Handshake() ERROR %+v\n", err) return nil, err } return tlsConn, nil @@ -465,12 +496,12 @@ func runClient(configFileName *string) { serverListToLog, ) - log.Printf( - "runClient(): I am listening on %s for SOCKS5 forward proxy \n", - config.TunneledOutboundSOCKS5ListenAddress, - ) - if forwardProxyListener != nil { + log.Printf( + "runClient(): I am listening on %s for SOCKS5 forward proxy \n", + config.TunneledOutboundSOCKS5ListenAddress, + ) + for { conn, err := forwardProxyListener.Accept() if err != nil { From 6cfcabd522ddd0d097b345af2f01181522e4aeae Mon Sep 17 00:00:00 2001 From: forest Date: Mon, 27 Sep 2021 11:37:34 -0500 Subject: [PATCH 36/36] add picopublish build script for the greenhouse installer --- picopublish.sh | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100755 picopublish.sh diff --git a/picopublish.sh b/picopublish.sh new file mode 100755 index 0000000..77d7559 --- /dev/null +++ b/picopublish.sh @@ -0,0 +1,34 @@ +#!/bin/bash -e + +function build() { + GOOS=$1 + GOARCH=$2 + tag="0.0.0" + if git describe --tags --abbrev=0 > /dev/null 2>&1 ; then + tag="$(git describe --tags --abbrev=0)" + fi + version="$tag-$(git rev-parse --short HEAD)-$(hexdump -n 2 -ve '1/1 "%.2x"' /dev/urandom)" + + echo "building version: $version" + + rm -rf build + mkdir build + + go build -tags 'osusergo netgo' -ldflags='-extldflags=-static' -o build/threshold + + sha256sum build/threshold + + gzip_file_name="threshold-$version-$GOOS-$GOARCH.gz" + + gzip --stdout build/threshold > "build/$gzip_file_name" + + curl -X POST "https://picopublish.sequentialread.com/files/$gzip_file_name" \ + -H 'Content-Type: application/x-gzip' -H "Authorization: Basic $(cat ~/.picopublish-auth)" \ + --data-binary "@build/$gzip_file_name" + + echo "https://picopublish.sequentialread.com/files/$gzip_file_name" +} + +#build arm +build linux amd64 +#build arm64 \ No newline at end of file