You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
virt/gateway/agent/auth.go

122 lines
4.1 KiB
Go

package agent
import (
"bytes"
"context"
"crypto/tls"
"encoding/json"
"errors"
"io"
"net"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"git.luoli.live/root/virt/gateway/internal/protocol"
)
const maxPanelResponseBytes = 64 << 10
type ConnectionAuthenticator interface {
Authenticate(context.Context, string, string) error
}
type HTTPConnectionAuthenticator struct {
endpoint string
secret []byte
client *http.Client
now func() time.Time
}
func NewHTTPConnectionAuthenticator(endpoint string, secret []byte, timeout time.Duration) (*HTTPConnectionAuthenticator, error) {
if err := validateLoopbackPanelURL(endpoint, "/api/internal/cloud/agent-auth"); err != nil {
return nil, err
}
if len(secret) < 32 || timeout <= 0 || timeout > 30*time.Second {
return nil, errors.New("invalid Agent authentication client settings")
}
dialer := &net.Dialer{Timeout: timeout, KeepAlive: 30 * time.Second}
transport := &http.Transport{
Proxy: nil, DialContext: dialer.DialContext, ForceAttemptHTTP2: false,
TLSClientConfig: &tls.Config{MinVersion: tls.VersionTLS12}, TLSHandshakeTimeout: timeout,
}
return &HTTPConnectionAuthenticator{
endpoint: endpoint,
secret: append([]byte(nil), secret...),
client: &http.Client{Transport: transport, Timeout: timeout,
CheckRedirect: func(_ *http.Request, _ []*http.Request) error { return http.ErrUseLastResponse }},
now: time.Now,
}, nil
}
func (a *HTTPConnectionAuthenticator) Authenticate(ctx context.Context, agentID, agentSecret string) error {
body, err := json.Marshal(struct {
AgentID string `json:"agent_id"`
AgentSecret string `json:"agent_secret"`
}{AgentID: agentID, AgentSecret: agentSecret})
if err != nil {
return errors.New("encode Agent authentication request")
}
request, err := http.NewRequestWithContext(ctx, http.MethodPost, a.endpoint, bytes.NewReader(body))
if err != nil {
return errors.New("create Agent authentication request")
}
request.Header.Set("Accept", "application/json")
request.Header.Set("Content-Type", "application/json")
nonce, err := protocol.RandomNonce()
if err != nil {
return errors.New("create Agent authentication nonce")
}
if err := protocol.Sign(request, body, protocol.Actor{Service: "agent-gateway"}, a.secret, a.now(), nonce); err != nil {
return errors.New("sign Agent authentication request")
}
response, err := a.client.Do(request)
if err != nil {
return errors.New("panel Agent authentication unavailable")
}
defer response.Body.Close()
raw, err := io.ReadAll(io.LimitReader(response.Body, maxPanelResponseBytes+1))
if err != nil || len(raw) > maxPanelResponseBytes || response.StatusCode != http.StatusOK {
return errors.New("panel rejected Agent authentication")
}
decoder := json.NewDecoder(bytes.NewReader(raw))
decoder.DisallowUnknownFields()
var result struct {
Active bool `json:"active"`
AgentID string `json:"agent_id"`
}
if err := decoder.Decode(&result); err != nil {
return errors.New("panel Agent authentication response is invalid")
}
var extra any
if err := decoder.Decode(&extra); !errors.Is(err, io.EOF) || !result.Active || result.AgentID != agentID {
return errors.New("panel rejected Agent authentication")
}
return nil
}
func validateLoopbackPanelURL(value, requiredPath string) error {
if value == "" || len(value) > 2048 || strings.ContainsAny(value, "\x00\r\n\\") {
return errors.New("panel internal URL is invalid")
}
parsed, err := url.Parse(value)
if err != nil || (parsed.Scheme != "http" && parsed.Scheme != "https") || parsed.User != nil ||
parsed.RawQuery != "" || parsed.ForceQuery || parsed.Fragment != "" || parsed.Path != requiredPath || parsed.RawPath != "" ||
strings.HasSuffix(parsed.Host, ":") {
return errors.New("panel internal URL must use its fixed path")
}
ip := net.ParseIP(parsed.Hostname())
if ip == nil || !ip.IsLoopback() {
return errors.New("panel internal URL must use a literal loopback address")
}
if port := parsed.Port(); port != "" {
number, err := strconv.Atoi(port)
if err != nil || number < 1 || number > 65535 {
return errors.New("panel internal URL has an invalid port")
}
}
return nil
}