diff --git a/Changes b/Changes index 799b87e..c6362d7 100644 --- a/Changes +++ b/Changes @@ -5,6 +5,7 @@ next: - add check_snclient_* / CHECK_SNCLIENT_* environment variables; the old check_nsc_web_* / CHECK_NSC_WEB_* variables are deprecated but still supported for backwards compatibility - send client timeout as X-Snclient-Timeout header; the legacy X-Nsc-Web-Timeout header is still sent for backwards compatibility - fix integer performance values being printed with fractions when using -f argument + - add -proxy flag and CHECK_SNCLIENT_PROXY environment variable 0.7.6 Fri Apr 10 16:12:37 CEST 2026 - minimum go version is now 1.26 diff --git a/README.md b/README.md index 2230d5e..743267c 100644 --- a/README.md +++ b/README.md @@ -91,6 +91,9 @@ Description: check_snclient is a REST client for the NSClient++/SNClient webserver for querying and receiving check information over HTTP(S). +Version: + check_snclient vX.Y.Z + Example: connectivity check (parent service): check_snclient -p "password" -u "https://:8443" @@ -110,6 +113,7 @@ Options: -a API version of SNClient/NSClient++ (legacy or 1) Default: legacy -l REST webserver login. Default: admin -p REST webserver password + -proxy Proxy URL or "env" (see Go net/http proxy documentation) -config Path to config file TLS/SSL Options: @@ -121,6 +125,25 @@ TLS/SSL Options: -tlshostname Use this servername when verifying tls server name -k Insecure mode - skip TLS verification +Environment Variables: + Command line options take predence over environment variables. + + check_snclient_password REST webserver password + CHECK_SNCLIENT_PASSWORD + check_snclient_login REST webserver login + CHECK_SNCLIENT_LOGIN + check_snclient_timeout Connection timeout in seconds + Optional set timeout state: 0-3 or OK, WARNING, CRITICAL, UNKNOWN + (default timeout state is UNKNOWN) + CHECK_SNCLIENT_TIMEOUT + check_snclient_proxy Proxy URL or "env" (see Go net/http proxy documentation) + CHECK_SNCLIENT_PROXY + check_snclient_proxy_url + CHECK_SNCLIENT_PROXY_URL + + The old check_nsc_web_* / CHECK_NSC_WEB_* variables are deprecated + but still supported for backwards compatibility. + Output Options: -h Print help -v Enable verbose output diff --git a/pkg/checksnclient/check.go b/pkg/checksnclient/check.go index 885152f..3d31ea4 100644 --- a/pkg/checksnclient/check.go +++ b/pkg/checksnclient/check.go @@ -73,6 +73,7 @@ Options: -a API version of SNClient/NSClient++ (legacy or 1) Default: legacy -l REST webserver login. Default: admin -p REST webserver password + -proxy Proxy URL or "env" (see Go net/http proxy documentation) -config Path to config file TLS/SSL Options: @@ -95,6 +96,10 @@ Environment Variables: Optional set timeout state: 0-3 or OK, WARNING, CRITICAL, UNKNOWN (default timeout state is UNKNOWN) CHECK_SNCLIENT_TIMEOUT + check_snclient_proxy Proxy URL or "env" (see Go net/http proxy documentation) + CHECK_SNCLIENT_PROXY + check_snclient_proxy_url + CHECK_SNCLIENT_PROXY_URL The old check_nsc_web_* / CHECK_NSC_WEB_* variables are deprecated but still supported for backwards compatibility. @@ -193,6 +198,7 @@ type flagSet struct { URL string Login string Password string + Proxy string APIVersion string Timeout string ErrorExit string @@ -472,6 +478,11 @@ func parseEnvironmentVariables(flags *flagSet, env []string) { case "check_snclient_timeout", "CHECK_SNCLIENT_TIMEOUT", "check_nsc_web_timeout", "CHECK_NSC_WEB_TIMEOUT": flags.Timeout = value + case "check_snclient_proxy", "CHECK_SNCLIENT_PROXY", + "check_snclient_proxy_url", "CHECK_SNCLIENT_PROXY_URL", + "check_nsc_web_proxy", "CHECK_NSC_WEB_PROXY", + "check_nsc_web_proxy_url", "CHECK_NSC_WEB_PROXY_URL": + flags.Proxy = value } } } @@ -483,6 +494,7 @@ func parseFlagsAndEnvironment(osArgs, env []string, output io.Writer) (flags *fl flagSet.StringVar(&flags.URL, "u", "", "SNClient URL, for example https://10.1.2.3:8443") flagSet.StringVar(&flags.Login, "l", "admin", "SNClient webserver login") flagSet.StringVar(&flags.Password, "p", "", "SNClient webserver password") + flagSet.StringVar(&flags.Proxy, "proxy", "", "Proxy URL or \"env\" (see Go net/http proxy documentation)") flagSet.StringVar(&flags.APIVersion, "a", "legacy", "API version of SNClient (legacy or 1)") flagSet.StringVar(&flags.Timeout, "t", "10:UNKNOWN", "Connection timeout in seconds") flagSet.StringVar(&flags.ErrorExit, "e", "UNKNOWN", "Connection error exit code.") @@ -735,8 +747,14 @@ func buildHTTPClient(output io.Writer, flags *flagSet, timeout time.Duration) (* return nil, err } + proxyFunc, err := getProxyFunc(flags.Proxy) + if err != nil { + return nil, err + } + hTransport := &http.Transport{ TLSClientConfig: tlsConfig, + Proxy: proxyFunc, DialContext: (&net.Dialer{ Timeout: timeout, }).DialContext, @@ -752,6 +770,37 @@ func buildHTTPClient(output io.Writer, flags *flagSet, timeout time.Duration) (* return hClient, nil } +func getProxyFunc(proxyStr string) (func(*http.Request) (*url.URL, error), error) { + if proxyStr == "" || strings.EqualFold(proxyStr, "none") || strings.EqualFold(proxyStr, "direct") { + return nil, nil + } + + if strings.EqualFold(proxyStr, "env") { + return http.ProxyFromEnvironment, nil + } + + if !strings.Contains(proxyStr, "://") { + proxyStr = "http://" + proxyStr + } + + proxyURL, err := url.Parse(proxyStr) + if err != nil { + return nil, fmt.Errorf("invalid proxy url: %s", err.Error()) + } + + if proxyURL.Host == "" { + return nil, fmt.Errorf("invalid proxy url: missing host") + } + + switch proxyURL.Scheme { + case "http", "https", "socks5": + default: + return nil, fmt.Errorf("unsupported proxy scheme: %s (only http, https and socks5 are supported)", proxyURL.Scheme) + } + + return http.ProxyURL(proxyURL), nil +} + func extractResult(output io.Writer, flags *flagSet, contents []byte) (*queryV1, error) { queryResult := &queryV1{} if flags.APIVersion == "1" { diff --git a/pkg/checksnclient/check_test.go b/pkg/checksnclient/check_test.go index e1032a7..89c3231 100644 --- a/pkg/checksnclient/check_test.go +++ b/pkg/checksnclient/check_test.go @@ -2,6 +2,8 @@ package checksnclient import ( "bytes" + "net/http" + "net/http/httptest" "os" "path/filepath" "testing" @@ -66,10 +68,19 @@ func TestParseEnvironmentVariables(t *testing.T) { "check_snclient_password=newpass", "CHECK_SNCLIENT_LOGIN=newlogin", "check_snclient_timeout=30", + "CHECK_SNCLIENT_PROXY=http://proxy:8080", }) assert.Equal(t, "newpass", flags.Password) assert.Equal(t, "newlogin", flags.Login) assert.Equal(t, "30", flags.Timeout) + assert.Equal(t, "http://proxy:8080", flags.Proxy) + + // The check_snclient_proxy_url alias. + flags = &flagSet{} + parseEnvironmentVariables(flags, []string{ + "check_snclient_proxy_url=http://proxy-url:8080", + }) + assert.Equal(t, "http://proxy-url:8080", flags.Proxy) // The deprecated check_nsc_web_* names must keep working. flags = &flagSet{} @@ -77,10 +88,12 @@ func TestParseEnvironmentVariables(t *testing.T) { "check_nsc_web_password=oldpass", "CHECK_NSC_WEB_LOGIN=oldlogin", "check_nsc_web_timeout=60", + "check_nsc_web_proxy=http://oldproxy:8080", }) assert.Equal(t, "oldpass", flags.Password) assert.Equal(t, "oldlogin", flags.Login) assert.Equal(t, "60", flags.Timeout) + assert.Equal(t, "http://oldproxy:8080", flags.Proxy) } func TestBuildRequestTimeoutHeader(t *testing.T) { @@ -96,3 +109,92 @@ func TestBuildRequestTimeoutHeader(t *testing.T) { assert.Equal(t, "5.00", req.Header.Get("X-Snclient-Timeout")) assert.Equal(t, "5.00", req.Header.Get("X-Nsc-Web-Timeout")) } + +func TestGetProxyFunc(t *testing.T) { + dummyReq, _ := http.NewRequest(http.MethodGet, "http://target.example.com", http.NoBody) + + // empty / none / direct + for _, val := range []string{"", "none", "NONE", "direct", "DIRECT"} { + fn, err := getProxyFunc(val) + require.NoError(t, err) + assert.Nil(t, fn) + } + + // env + t.Setenv("HTTP_PROXY", "http://envproxy:8080") + fn, err := getProxyFunc("env") + require.NoError(t, err) + require.NotNil(t, fn) + proxyURL, err := fn(dummyReq) + require.NoError(t, err) + require.NotNil(t, proxyURL) + assert.Equal(t, "http://envproxy:8080", proxyURL.String()) + + // standard URL + fn, err = getProxyFunc("http://127.0.0.1:8080") + require.NoError(t, err) + require.NotNil(t, fn) + proxyURL, err = fn(dummyReq) + require.NoError(t, err) + assert.Equal(t, "http://127.0.0.1:8080", proxyURL.String()) + + // URL with credentials + fn, err = getProxyFunc("http://user:secret@127.0.0.1:8080") + require.NoError(t, err) + require.NotNil(t, fn) + proxyURL, err = fn(dummyReq) + require.NoError(t, err) + assert.Equal(t, "http://user:secret@127.0.0.1:8080", proxyURL.String()) + + // auto-prepend http:// + fn, err = getProxyFunc("127.0.0.1:3128") + require.NoError(t, err) + require.NotNil(t, fn) + proxyURL, err = fn(dummyReq) + require.NoError(t, err) + assert.Equal(t, "http://127.0.0.1:3128", proxyURL.String()) + + // socks5 + fn, err = getProxyFunc("socks5://127.0.0.1:1080") + require.NoError(t, err) + require.NotNil(t, fn) + proxyURL, err = fn(dummyReq) + require.NoError(t, err) + assert.Equal(t, "socks5://127.0.0.1:1080", proxyURL.String()) + + // unsupported scheme + _, err = getProxyFunc("ftp://127.0.0.1:21") + require.Error(t, err) + assert.Contains(t, err.Error(), "unsupported proxy scheme: ftp") + + // missing host + _, err = getProxyFunc("http://") + require.Error(t, err) + assert.Contains(t, err.Error(), "missing host") +} + +func TestCheckWithProxy(t *testing.T) { + ctx := t.Context() + buf := &bytes.Buffer{} + + proxyHit := false + proxyServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + proxyHit = true + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`{"command":"check_cpu","result":0,"lines":[{"message":"OK - cpu 5%"}]}`)) + })) + defer proxyServer.Close() + + exitCode := Check(ctx, buf, []string{ + "-u", "http://unreachable-host-example.test:8443", + "-p", "secret", + "-a", "1", + "-proxy", proxyServer.URL, + "check_cpu", + }, nil) + + assert.True(t, proxyHit, "request must pass through proxy") + assert.Equal(t, 0, exitCode) + assert.Contains(t, buf.String(), "OK - cpu 5%") +}