feat(check): add http, tcp, tls, dns and icmp checks
Validate normalizes settings for the API; Run executes them on checkers. Targets on private networks are refused unless explicitly allowed. Refs #12 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
This commit is contained in:
1 parent
bc8e934568
commit
55559c8b0a
6 files changed
+710
-1
No files matched your search
@@ -0,0 +1,129 @@
|
||||
// Package check runs a single uptime check and validates check settings.
|
||||
//
|
||||
// The API validates monitor settings with Validate before storing them, and
|
||||
// checkers execute them with Run, so both sides agree on what a setting
|
||||
// means.
|
||||
package check
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Type names a kind of check. The values are stored in the database.
|
||||
type Type string
|
||||
|
||||
// Check types.
|
||||
const (
|
||||
HTTP Type = "http"
|
||||
TCP Type = "tcp"
|
||||
ICMP Type = "icmp"
|
||||
DNS Type = "dns"
|
||||
TLS Type = "tls"
|
||||
)
|
||||
|
||||
// Types lists every check type.
|
||||
var Types = []Type{HTTP, TCP, ICMP, DNS, TLS}
|
||||
|
||||
// Spec is everything needed to run one check.
|
||||
type Spec struct {
|
||||
Type Type
|
||||
Target string
|
||||
Timeout time.Duration
|
||||
Config json.RawMessage
|
||||
// AllowPrivate permits targets on private networks. It is false for
|
||||
// shared checkers in the cloud edition.
|
||||
AllowPrivate bool
|
||||
}
|
||||
|
||||
// Outcome is the result of one check run.
|
||||
type Outcome struct {
|
||||
OK bool
|
||||
Latency time.Duration
|
||||
// StatusCode is the HTTP status, or 0 for other types.
|
||||
StatusCode int
|
||||
// Error explains a failure in a form suitable for showing to customers.
|
||||
Error string
|
||||
}
|
||||
|
||||
// ErrInvalid is wrapped by Validate errors. Its message is the code shown to
|
||||
// API clients, e.g. "invalid_target".
|
||||
type ErrInvalid struct{ Code string }
|
||||
|
||||
func (e ErrInvalid) Error() string { return "check: " + e.Code }
|
||||
|
||||
func invalid(code string) error { return ErrInvalid{Code: code} }
|
||||
|
||||
type runner interface {
|
||||
run(ctx context.Context, s Spec) Outcome
|
||||
}
|
||||
|
||||
type validator interface {
|
||||
// validate checks target and config and returns the config with
|
||||
// defaults applied.
|
||||
validate(target string, config json.RawMessage) (json.RawMessage, error)
|
||||
}
|
||||
|
||||
type impl interface {
|
||||
runner
|
||||
validator
|
||||
}
|
||||
|
||||
var impls = map[Type]impl{
|
||||
HTTP: httpCheck{},
|
||||
TCP: tcpCheck{},
|
||||
ICMP: icmpCheck{},
|
||||
DNS: dnsCheck{},
|
||||
TLS: tlsCheck{},
|
||||
}
|
||||
|
||||
// Validate checks target and config for type t and returns the normalized
|
||||
// config. Errors are ErrInvalid.
|
||||
func Validate(t Type, target string, config json.RawMessage) (json.RawMessage, error) {
|
||||
im, ok := impls[t]
|
||||
if !ok {
|
||||
return nil, invalid("invalid_type")
|
||||
}
|
||||
if len(config) == 0 || string(config) == "null" {
|
||||
config = json.RawMessage("{}")
|
||||
}
|
||||
return im.validate(target, config)
|
||||
}
|
||||
|
||||
// Run executes s. It never panics on bad input; problems become a failed
|
||||
// Outcome.
|
||||
func Run(ctx context.Context, s Spec) Outcome {
|
||||
im, ok := impls[s.Type]
|
||||
if !ok {
|
||||
return Outcome{Error: "unknown check type"}
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(ctx, s.Timeout)
|
||||
defer cancel()
|
||||
start := time.Now()
|
||||
o := im.run(ctx, s)
|
||||
if o.Latency == 0 {
|
||||
o.Latency = time.Since(start)
|
||||
}
|
||||
if !o.OK && o.Error == "" {
|
||||
o.Error = "check failed"
|
||||
}
|
||||
if errors.Is(ctx.Err(), context.DeadlineExceeded) && !o.OK {
|
||||
o.Error = "timeout after " + s.Timeout.String()
|
||||
}
|
||||
return o
|
||||
}
|
||||
|
||||
func decode[T any](config json.RawMessage) (T, error) {
|
||||
var v T
|
||||
if err := json.Unmarshal(config, &v); err != nil {
|
||||
return v, invalid("invalid_config")
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
|
||||
func encode(v any) json.RawMessage {
|
||||
b, _ := json.Marshal(v)
|
||||
return b
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
package check
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func mustValidate(t *testing.T, typ Type, target, config string) json.RawMessage {
|
||||
t.Helper()
|
||||
c, err := Validate(typ, target, json.RawMessage(config))
|
||||
if err != nil {
|
||||
t.Fatalf("Validate(%s, %q, %s) failed: %v", typ, target, config, err)
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
func run(t *testing.T, typ Type, target, config string) Outcome {
|
||||
t.Helper()
|
||||
return Run(context.Background(), Spec{
|
||||
Type: typ, Target: target, Timeout: 2 * time.Second,
|
||||
Config: mustValidate(t, typ, target, config), AllowPrivate: true,
|
||||
})
|
||||
}
|
||||
|
||||
func TestHTTP(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.URL.Path {
|
||||
case "/ok":
|
||||
_, _ = w.Write([]byte("all systems operational"))
|
||||
case "/fail":
|
||||
w.WriteHeader(http.StatusServiceUnavailable)
|
||||
case "/moved":
|
||||
http.Redirect(w, r, "/ok", http.StatusMovedPermanently)
|
||||
case "/slow":
|
||||
time.Sleep(3 * time.Second)
|
||||
}
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
tests := []struct {
|
||||
name, path, config string
|
||||
wantOK bool
|
||||
wantErr string
|
||||
}{
|
||||
{"ok", "/ok", `{}`, true, ""},
|
||||
{"server error", "/fail", `{}`, false, "unexpected status 503"},
|
||||
{"accepted error code", "/fail", `{"expect_status":["503"]}`, true, ""},
|
||||
{"keyword present", "/ok", `{"keyword":"operational"}`, true, ""},
|
||||
{"keyword missing", "/ok", `{"keyword":"outage"}`, false, "keyword not found"},
|
||||
{"keyword must be absent", "/ok", `{"keyword":"operational","keyword_absent":true}`, false, "keyword present"},
|
||||
{"redirect followed", "/moved", `{"expect_status":["200"]}`, true, ""},
|
||||
{"redirect not followed", "/moved", `{"expect_status":["200"],"follow_redirects":false}`, false, "unexpected status 301"},
|
||||
{"timeout", "/slow", `{}`, false, "timeout after 2s"},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
o := run(t, HTTP, srv.URL+tt.path, tt.config)
|
||||
if o.OK != tt.wantOK || o.Error != tt.wantErr {
|
||||
t.Errorf("Run() = ok %t err %q, want ok %t err %q", o.OK, o.Error, tt.wantOK, tt.wantErr)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestPrivateTargetsBlocked(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}))
|
||||
defer srv.Close()
|
||||
host := strings.TrimPrefix(srv.URL, "http://")
|
||||
for _, s := range []Spec{
|
||||
{Type: HTTP, Target: srv.URL, Config: mustValidate(t, HTTP, srv.URL, `{}`)},
|
||||
{Type: TCP, Target: host, Config: json.RawMessage(`{}`)},
|
||||
} {
|
||||
s.Timeout = time.Second
|
||||
if o := Run(context.Background(), s); o.OK || o.Error != "target resolves to a non-public address" {
|
||||
t.Errorf("Run(%s %s) without AllowPrivate = %+v, want blocked", s.Type, s.Target, o)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestTCP(t *testing.T) {
|
||||
ln, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
addr := ln.Addr().String()
|
||||
if o := run(t, TCP, addr, `{}`); !o.OK {
|
||||
t.Errorf("Run(tcp open port) = %+v, want ok", o)
|
||||
}
|
||||
_ = ln.Close()
|
||||
if o := run(t, TCP, addr, `{}`); o.OK || !strings.HasPrefix(o.Error, "connection failed") {
|
||||
t.Errorf("Run(tcp closed port) = %+v, want connection failed", o)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTLS(t *testing.T) {
|
||||
srv := httptest.NewTLSServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}))
|
||||
defer srv.Close()
|
||||
host := strings.TrimPrefix(srv.URL, "https://")
|
||||
// The httptest certificate is self-signed, so verification fails; that
|
||||
// is reported like any other TLS problem.
|
||||
if o := run(t, TLS, host, `{"server_name":"example.com"}`); o.OK || !strings.Contains(o.Error, "certificate") {
|
||||
t.Errorf("Run(tls self-signed) = %+v, want certificate error", o)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidate(t *testing.T) {
|
||||
tests := []struct {
|
||||
typ Type
|
||||
target, config string
|
||||
want string
|
||||
}{
|
||||
{HTTP, "ftp://x", `{}`, "invalid_target"},
|
||||
{HTTP, "https://user:pw@x.test", `{}`, "invalid_target"},
|
||||
{HTTP, "https://x.test", `{"method":"POST"}`, "invalid_method"},
|
||||
{HTTP, "https://x.test", `{"method":"HEAD","keyword":"x"}`, "keyword_needs_get"},
|
||||
{HTTP, "https://x.test", `{"expect_status":["6xx"]}`, "invalid_expect_status"},
|
||||
{HTTP, "https://x.test", `{"headers":{"X":"a\r\nb"}}`, "invalid_header"},
|
||||
{TCP, "x.test", `{}`, "invalid_target"},
|
||||
{TCP, "x.test:0", `{}`, "invalid_target"},
|
||||
{DNS, "x.test", `{"record":"SRV"}`, "invalid_record"},
|
||||
{TLS, "x.test:443", `{"min_days_valid":-1}`, "invalid_config"},
|
||||
{"smtp", "x.test", `{}`, "invalid_type"},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
_, err := Validate(tt.typ, tt.target, json.RawMessage(tt.config))
|
||||
var inv ErrInvalid
|
||||
if !errors.As(err, &inv) || inv.Code != tt.want {
|
||||
t.Errorf("Validate(%s, %q, %s) = %v, want %s", tt.typ, tt.target, tt.config, err, tt.want)
|
||||
}
|
||||
}
|
||||
got := mustValidate(t, HTTP, "https://x.test", `{}`)
|
||||
want := `{"method":"GET","expect_status":["2xx","3xx"],"follow_redirects":true,"verify_tls":true}`
|
||||
if string(got) != want {
|
||||
t.Errorf("Validate(http defaults) = %s, want %s", got, want)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
package check
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/netguard"
|
||||
)
|
||||
|
||||
// HTTPConfig configures an HTTP(S) check.
|
||||
type HTTPConfig struct {
|
||||
Method string `json:"method"`
|
||||
// ExpectStatus lists accepted codes or classes such as "2xx" or "301".
|
||||
ExpectStatus []string `json:"expect_status"`
|
||||
// Keyword must appear in the body, or must not if KeywordAbsent is set.
|
||||
Keyword string `json:"keyword,omitempty"`
|
||||
KeywordAbsent bool `json:"keyword_absent,omitempty"`
|
||||
FollowRedirects bool `json:"follow_redirects"`
|
||||
VerifyTLS bool `json:"verify_tls"`
|
||||
Headers map[string]string `json:"headers,omitempty"`
|
||||
}
|
||||
|
||||
// maxBody bounds how much of a response is searched for the keyword.
|
||||
const maxBody = 1 << 20
|
||||
|
||||
type httpCheck struct{}
|
||||
|
||||
func (httpCheck) validate(target string, config json.RawMessage) (json.RawMessage, error) {
|
||||
u, err := url.Parse(target)
|
||||
if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" || u.User != nil {
|
||||
return nil, invalid("invalid_target")
|
||||
}
|
||||
c := HTTPConfig{Method: http.MethodGet, ExpectStatus: []string{"2xx", "3xx"}, FollowRedirects: true, VerifyTLS: true}
|
||||
if err := json.Unmarshal(config, &c); err != nil {
|
||||
return nil, invalid("invalid_config")
|
||||
}
|
||||
c.Method = strings.ToUpper(c.Method)
|
||||
if c.Method != http.MethodGet && c.Method != http.MethodHead {
|
||||
return nil, invalid("invalid_method")
|
||||
}
|
||||
if c.Method == http.MethodHead && c.Keyword != "" {
|
||||
return nil, invalid("keyword_needs_get")
|
||||
}
|
||||
if len(c.ExpectStatus) == 0 || len(c.ExpectStatus) > 20 {
|
||||
return nil, invalid("invalid_expect_status")
|
||||
}
|
||||
for _, p := range c.ExpectStatus {
|
||||
if !validStatusPattern(p) {
|
||||
return nil, invalid("invalid_expect_status")
|
||||
}
|
||||
}
|
||||
if len(c.Keyword) > 500 || len(c.Headers) > 20 {
|
||||
return nil, invalid("invalid_config")
|
||||
}
|
||||
for k, v := range c.Headers {
|
||||
if k == "" || strings.ContainsAny(k+v, "\r\n") || strings.EqualFold(k, "Host") {
|
||||
return nil, invalid("invalid_header")
|
||||
}
|
||||
}
|
||||
return encode(c), nil
|
||||
}
|
||||
|
||||
func validStatusPattern(p string) bool {
|
||||
if len(p) == 3 && p[1:] == "xx" {
|
||||
return p[0] >= '1' && p[0] <= '5'
|
||||
}
|
||||
n, err := strconv.Atoi(p)
|
||||
return err == nil && n >= 100 && n <= 599
|
||||
}
|
||||
|
||||
func statusMatches(code int, patterns []string) bool {
|
||||
s := strconv.Itoa(code)
|
||||
for _, p := range patterns {
|
||||
if p == s || (strings.HasSuffix(p, "xx") && p[0] == s[0]) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (httpCheck) run(ctx context.Context, s Spec) Outcome {
|
||||
c, err := decode[HTTPConfig](s.Config)
|
||||
if err != nil {
|
||||
return Outcome{Error: "invalid configuration"}
|
||||
}
|
||||
d := netguard.Dialer(s.AllowPrivate, s.Timeout)
|
||||
tr := &http.Transport{
|
||||
DialContext: d.DialContext,
|
||||
TLSClientConfig: &tls.Config{InsecureSkipVerify: !c.VerifyTLS}, //nolint:gosec // opt-out chosen by the customer per monitor
|
||||
DisableKeepAlives: true,
|
||||
TLSHandshakeTimeout: s.Timeout,
|
||||
ForceAttemptHTTP2: true,
|
||||
}
|
||||
defer tr.CloseIdleConnections()
|
||||
client := &http.Client{Transport: tr}
|
||||
if !c.FollowRedirects {
|
||||
client.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, c.Method, s.Target, nil)
|
||||
if err != nil {
|
||||
return Outcome{Error: "invalid target"}
|
||||
}
|
||||
req.Header.Set("User-Agent", "uptimesebi-checker")
|
||||
for k, v := range c.Headers {
|
||||
req.Header.Set(k, v)
|
||||
}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return Outcome{Error: describeNetErr(err)}
|
||||
}
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
o := Outcome{StatusCode: resp.StatusCode}
|
||||
if !statusMatches(resp.StatusCode, c.ExpectStatus) {
|
||||
o.Error = fmt.Sprintf("unexpected status %d", resp.StatusCode)
|
||||
return o
|
||||
}
|
||||
if c.Keyword != "" {
|
||||
body, err := io.ReadAll(io.LimitReader(resp.Body, maxBody))
|
||||
if err != nil {
|
||||
o.Error = describeNetErr(err)
|
||||
return o
|
||||
}
|
||||
found := bytes.Contains(body, []byte(c.Keyword))
|
||||
switch {
|
||||
case found && c.KeywordAbsent:
|
||||
o.Error = "keyword present"
|
||||
return o
|
||||
case !found && !c.KeywordAbsent:
|
||||
o.Error = "keyword not found"
|
||||
return o
|
||||
}
|
||||
}
|
||||
o.OK = true
|
||||
return o
|
||||
}
|
||||
|
||||
// describeNetErr turns transport errors into short, stable messages.
|
||||
func describeNetErr(err error) string {
|
||||
var dnsErr *net.DNSError
|
||||
var certErr *tls.CertificateVerificationError
|
||||
var opErr *net.OpError
|
||||
switch {
|
||||
case errors.Is(err, netguard.ErrForbiddenAddress):
|
||||
return "target resolves to a non-public address"
|
||||
case errors.Is(err, context.DeadlineExceeded):
|
||||
return "timeout"
|
||||
case errors.As(err, &dnsErr):
|
||||
if dnsErr.IsNotFound {
|
||||
return "host not found"
|
||||
}
|
||||
return "dns lookup failed"
|
||||
case errors.As(err, &certErr):
|
||||
return "tls certificate invalid: " + certErr.Err.Error()
|
||||
case errors.As(err, &opErr):
|
||||
if opErr.Op == "dial" {
|
||||
return "connection failed: " + opErr.Err.Error()
|
||||
}
|
||||
return opErr.Op + " failed: " + opErr.Err.Error()
|
||||
}
|
||||
return err.Error()
|
||||
}
|
||||
@@ -0,0 +1,264 @@
|
||||
package check
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/netip"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"golang.org/x/net/icmp"
|
||||
"golang.org/x/net/ipv4"
|
||||
"golang.org/x/net/ipv6"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/netguard"
|
||||
)
|
||||
|
||||
func validHostPort(target string) bool {
|
||||
host, port, err := net.SplitHostPort(target)
|
||||
if err != nil || host == "" {
|
||||
return false
|
||||
}
|
||||
p, err := strconv.Atoi(port)
|
||||
return err == nil && p > 0 && p < 65536
|
||||
}
|
||||
|
||||
func validHost(host string) bool {
|
||||
if _, err := netip.ParseAddr(host); err == nil {
|
||||
return true
|
||||
}
|
||||
if len(host) == 0 || len(host) > 253 || strings.ContainsAny(host, "/:@ ") {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
type tcpCheck struct{}
|
||||
|
||||
func (tcpCheck) validate(target string, config json.RawMessage) (json.RawMessage, error) {
|
||||
if !validHostPort(target) {
|
||||
return nil, invalid("invalid_target")
|
||||
}
|
||||
return json.RawMessage("{}"), nil
|
||||
}
|
||||
|
||||
func (tcpCheck) run(ctx context.Context, s Spec) Outcome {
|
||||
start := time.Now()
|
||||
conn, err := netguard.Dialer(s.AllowPrivate, s.Timeout).DialContext(ctx, "tcp", s.Target)
|
||||
if err != nil {
|
||||
return Outcome{Error: describeNetErr(err)}
|
||||
}
|
||||
o := Outcome{OK: true, Latency: time.Since(start)}
|
||||
_ = conn.Close()
|
||||
return o
|
||||
}
|
||||
|
||||
// TLSConfig configures a certificate expiry check.
|
||||
type TLSConfig struct {
|
||||
// MinDaysValid fails the check when the leaf certificate expires sooner.
|
||||
MinDaysValid int `json:"min_days_valid"`
|
||||
// ServerName overrides SNI and verification name; defaults to the host.
|
||||
ServerName string `json:"server_name,omitempty"`
|
||||
}
|
||||
|
||||
type tlsCheck struct{}
|
||||
|
||||
func (tlsCheck) validate(target string, config json.RawMessage) (json.RawMessage, error) {
|
||||
if !validHostPort(target) {
|
||||
return nil, invalid("invalid_target")
|
||||
}
|
||||
c := TLSConfig{MinDaysValid: 14}
|
||||
if err := json.Unmarshal(config, &c); err != nil {
|
||||
return nil, invalid("invalid_config")
|
||||
}
|
||||
if c.MinDaysValid < 0 || c.MinDaysValid > 365 || (c.ServerName != "" && !validHost(c.ServerName)) {
|
||||
return nil, invalid("invalid_config")
|
||||
}
|
||||
return encode(c), nil
|
||||
}
|
||||
|
||||
func (tlsCheck) run(ctx context.Context, s Spec) Outcome {
|
||||
c, err := decode[TLSConfig](s.Config)
|
||||
if err != nil {
|
||||
return Outcome{Error: "invalid configuration"}
|
||||
}
|
||||
host, _, _ := net.SplitHostPort(s.Target)
|
||||
if c.ServerName != "" {
|
||||
host = c.ServerName
|
||||
}
|
||||
d := &tls.Dialer{NetDialer: netguard.Dialer(s.AllowPrivate, s.Timeout), Config: &tls.Config{ServerName: host}}
|
||||
start := time.Now()
|
||||
conn, err := d.DialContext(ctx, "tcp", s.Target)
|
||||
if err != nil {
|
||||
return Outcome{Error: describeNetErr(err)}
|
||||
}
|
||||
latency := time.Since(start)
|
||||
defer func() { _ = conn.Close() }()
|
||||
certs := conn.(*tls.Conn).ConnectionState().PeerCertificates
|
||||
if len(certs) == 0 {
|
||||
return Outcome{Latency: latency, Error: "no certificate presented"}
|
||||
}
|
||||
left := time.Until(certs[0].NotAfter)
|
||||
if days := int(left.Hours() / 24); days < c.MinDaysValid {
|
||||
return Outcome{Latency: latency, Error: fmt.Sprintf("certificate expires in %d days", days)}
|
||||
}
|
||||
return Outcome{OK: true, Latency: latency}
|
||||
}
|
||||
|
||||
// DNSConfig configures a DNS check.
|
||||
type DNSConfig struct {
|
||||
Record string `json:"record"`
|
||||
// Resolver is host:port of the DNS server to ask; empty uses the
|
||||
// checker's resolver.
|
||||
Resolver string `json:"resolver,omitempty"`
|
||||
// Expect, if set, must be contained in one of the answers.
|
||||
Expect string `json:"expect,omitempty"`
|
||||
}
|
||||
|
||||
var dnsRecords = []string{"A", "AAAA", "CNAME", "MX", "NS", "TXT"}
|
||||
|
||||
type dnsCheck struct{}
|
||||
|
||||
func (dnsCheck) validate(target string, config json.RawMessage) (json.RawMessage, error) {
|
||||
if !validHost(target) {
|
||||
return nil, invalid("invalid_target")
|
||||
}
|
||||
c := DNSConfig{Record: "A"}
|
||||
if err := json.Unmarshal(config, &c); err != nil {
|
||||
return nil, invalid("invalid_config")
|
||||
}
|
||||
c.Record = strings.ToUpper(c.Record)
|
||||
if !slices.Contains(dnsRecords, c.Record) {
|
||||
return nil, invalid("invalid_record")
|
||||
}
|
||||
if c.Resolver != "" && !validHostPort(c.Resolver) {
|
||||
return nil, invalid("invalid_resolver")
|
||||
}
|
||||
if len(c.Expect) > 500 {
|
||||
return nil, invalid("invalid_config")
|
||||
}
|
||||
return encode(c), nil
|
||||
}
|
||||
|
||||
func (dnsCheck) run(ctx context.Context, s Spec) Outcome {
|
||||
c, err := decode[DNSConfig](s.Config)
|
||||
if err != nil {
|
||||
return Outcome{Error: "invalid configuration"}
|
||||
}
|
||||
r := net.DefaultResolver
|
||||
if c.Resolver != "" {
|
||||
d := netguard.Dialer(s.AllowPrivate, s.Timeout)
|
||||
r = &net.Resolver{PreferGo: true, Dial: func(ctx context.Context, network, _ string) (net.Conn, error) {
|
||||
return d.DialContext(ctx, network, c.Resolver)
|
||||
}}
|
||||
}
|
||||
var answers []string
|
||||
switch c.Record {
|
||||
case "A", "AAAA":
|
||||
network := "ip4"
|
||||
if c.Record == "AAAA" {
|
||||
network = "ip6"
|
||||
}
|
||||
ips, e := r.LookupNetIP(ctx, network, s.Target)
|
||||
for _, ip := range ips {
|
||||
answers = append(answers, ip.String())
|
||||
}
|
||||
err = e
|
||||
case "CNAME":
|
||||
var cname string
|
||||
cname, err = r.LookupCNAME(ctx, s.Target)
|
||||
answers = []string{cname}
|
||||
case "MX":
|
||||
var mx []*net.MX
|
||||
mx, err = r.LookupMX(ctx, s.Target)
|
||||
for _, m := range mx {
|
||||
answers = append(answers, m.Host)
|
||||
}
|
||||
case "NS":
|
||||
var ns []*net.NS
|
||||
ns, err = r.LookupNS(ctx, s.Target)
|
||||
for _, n := range ns {
|
||||
answers = append(answers, n.Host)
|
||||
}
|
||||
case "TXT":
|
||||
answers, err = r.LookupTXT(ctx, s.Target)
|
||||
}
|
||||
if err != nil {
|
||||
return Outcome{Error: describeNetErr(err)}
|
||||
}
|
||||
if len(answers) == 0 {
|
||||
return Outcome{Error: "no " + c.Record + " records"}
|
||||
}
|
||||
if c.Expect != "" && !slices.ContainsFunc(answers, func(a string) bool { return strings.Contains(a, c.Expect) }) {
|
||||
return Outcome{Error: "expected answer not found"}
|
||||
}
|
||||
return Outcome{OK: true}
|
||||
}
|
||||
|
||||
type icmpCheck struct{}
|
||||
|
||||
func (icmpCheck) validate(target string, config json.RawMessage) (json.RawMessage, error) {
|
||||
if !validHost(target) {
|
||||
return nil, invalid("invalid_target")
|
||||
}
|
||||
return json.RawMessage("{}"), nil
|
||||
}
|
||||
|
||||
// run sends one echo request over an unprivileged ICMP socket. The host must
|
||||
// allow it via net.ipv4.ping_group_range; otherwise the check reports that.
|
||||
func (icmpCheck) run(ctx context.Context, s Spec) Outcome {
|
||||
var addrs []netip.Addr
|
||||
var err error
|
||||
if s.AllowPrivate {
|
||||
addrs, err = net.DefaultResolver.LookupNetIP(ctx, "ip", s.Target)
|
||||
} else {
|
||||
addrs, err = netguard.CheckHost(ctx, s.Target)
|
||||
}
|
||||
if err != nil {
|
||||
return Outcome{Error: describeNetErr(err)}
|
||||
}
|
||||
if len(addrs) == 0 {
|
||||
return Outcome{Error: "host not found"}
|
||||
}
|
||||
addr := addrs[0].Unmap()
|
||||
network, proto, echo := "udp4", 1, icmp.Type(ipv4.ICMPTypeEcho)
|
||||
if addr.Is6() {
|
||||
network, proto, echo = "udp6", 58, ipv6.ICMPTypeEchoRequest
|
||||
}
|
||||
conn, err := icmp.ListenPacket(network, "")
|
||||
if err != nil {
|
||||
return Outcome{Error: "icmp not permitted on this checker: " + err.Error()}
|
||||
}
|
||||
defer func() { _ = conn.Close() }()
|
||||
if dl, ok := ctx.Deadline(); ok {
|
||||
_ = conn.SetDeadline(dl)
|
||||
}
|
||||
msg := icmp.Message{Type: echo, Body: &icmp.Echo{ID: 1, Seq: 1, Data: []byte("uptimesebi")}}
|
||||
b, err := msg.Marshal(nil)
|
||||
if err != nil {
|
||||
return Outcome{Error: err.Error()}
|
||||
}
|
||||
start := time.Now()
|
||||
if _, err := conn.WriteTo(b, &net.UDPAddr{IP: addr.AsSlice()}); err != nil {
|
||||
return Outcome{Error: describeNetErr(err)}
|
||||
}
|
||||
buf := make([]byte, 1500)
|
||||
for {
|
||||
n, _, err := conn.ReadFrom(buf)
|
||||
if err != nil {
|
||||
return Outcome{Error: "no echo reply"}
|
||||
}
|
||||
reply, err := icmp.ParseMessage(proto, buf[:n])
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
if reply.Type == ipv4.ICMPTypeEchoReply || reply.Type == ipv6.ICMPTypeEchoReply {
|
||||
return Outcome{OK: true, Latency: time.Since(start)}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user