fix(security): close six open GHSA findings from security triage
Harden share-link listing, password rotation, OIDC callback binding, org invite search, knowledge batch mutations, and connector redirects.
This commit is contained in:
@@ -0,0 +1,106 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"crypto/hmac"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
const oidcStateMaxAge = 10 * time.Minute
|
||||
|
||||
// OIDCStatePayload is the signed OIDC authorization state carried in the
|
||||
// redirect URL and validated on callback.
|
||||
type OIDCStatePayload struct {
|
||||
Nonce string `json:"nonce"`
|
||||
RedirectURI string `json:"redirect_uri,omitempty"`
|
||||
IssuedAt int64 `json:"iat"`
|
||||
}
|
||||
|
||||
var (
|
||||
oidcStateSecretOnce sync.Once
|
||||
oidcStateSecret string
|
||||
)
|
||||
|
||||
func oidcStateSigningKey() string {
|
||||
oidcStateSecretOnce.Do(func() {
|
||||
if envSecret := strings.TrimSpace(os.Getenv("JWT_SECRET")); envSecret != "" {
|
||||
oidcStateSecret = envSecret
|
||||
return
|
||||
}
|
||||
randomBytes := make([]byte, 32)
|
||||
if _, err := rand.Read(randomBytes); err != nil {
|
||||
panic(fmt.Sprintf("failed to generate OIDC state signing key: %v", err))
|
||||
}
|
||||
oidcStateSecret = base64.StdEncoding.EncodeToString(randomBytes)
|
||||
})
|
||||
return oidcStateSecret
|
||||
}
|
||||
|
||||
// SignOIDCState returns a tamper-evident state token: base64url(payload).base64url(hmac).
|
||||
func SignOIDCState(payload *OIDCStatePayload) (string, error) {
|
||||
if payload == nil {
|
||||
return "", errors.New("oidc state payload is required")
|
||||
}
|
||||
if strings.TrimSpace(payload.Nonce) == "" {
|
||||
return "", errors.New("oidc state nonce is required")
|
||||
}
|
||||
if strings.TrimSpace(payload.RedirectURI) == "" {
|
||||
return "", errors.New("oidc state redirect_uri is required")
|
||||
}
|
||||
if payload.IssuedAt == 0 {
|
||||
payload.IssuedAt = time.Now().Unix()
|
||||
}
|
||||
raw, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("marshal oidc state: %w", err)
|
||||
}
|
||||
mac := hmac.New(sha256.New, []byte(oidcStateSigningKey()))
|
||||
mac.Write(raw)
|
||||
sig := mac.Sum(nil)
|
||||
return base64.RawURLEncoding.EncodeToString(raw) + "." + base64.RawURLEncoding.EncodeToString(sig), nil
|
||||
}
|
||||
|
||||
// VerifyOIDCState validates the HMAC and freshness of a state token.
|
||||
func VerifyOIDCState(raw string) (*OIDCStatePayload, error) {
|
||||
raw = strings.TrimSpace(raw)
|
||||
parts := strings.Split(raw, ".")
|
||||
if len(parts) != 2 {
|
||||
return nil, errors.New("invalid oidc state format")
|
||||
}
|
||||
payloadBytes, err := base64.RawURLEncoding.DecodeString(parts[0])
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("decode oidc state payload: %w", err)
|
||||
}
|
||||
sigBytes, err := base64.RawURLEncoding.DecodeString(parts[1])
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("decode oidc state signature: %w", err)
|
||||
}
|
||||
mac := hmac.New(sha256.New, []byte(oidcStateSigningKey()))
|
||||
mac.Write(payloadBytes)
|
||||
if !hmac.Equal(mac.Sum(nil), sigBytes) {
|
||||
return nil, errors.New("oidc state signature mismatch")
|
||||
}
|
||||
var payload OIDCStatePayload
|
||||
if err := json.Unmarshal(payloadBytes, &payload); err != nil {
|
||||
return nil, fmt.Errorf("unmarshal oidc state: %w", err)
|
||||
}
|
||||
if strings.TrimSpace(payload.RedirectURI) == "" {
|
||||
return nil, errors.New("state.redirect_uri is required")
|
||||
}
|
||||
if payload.IssuedAt == 0 {
|
||||
return nil, errors.New("state.iat is required")
|
||||
}
|
||||
issuedAt := time.Unix(payload.IssuedAt, 0)
|
||||
if time.Since(issuedAt) > oidcStateMaxAge || time.Until(issuedAt) > time.Minute {
|
||||
return nil, errors.New("oidc state expired or invalid timestamp")
|
||||
}
|
||||
return &payload, nil
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestSignAndVerifyOIDCState(t *testing.T) {
|
||||
t.Setenv("JWT_SECRET", "test-oidc-state-secret")
|
||||
oidcStateSecretOnce = sync.Once{}
|
||||
oidcStateSecret = ""
|
||||
|
||||
state, err := SignOIDCState(&OIDCStatePayload{
|
||||
Nonce: "nonce-abc",
|
||||
RedirectURI: "http://localhost:5173/login",
|
||||
IssuedAt: time.Now().Unix(),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("SignOIDCState: %v", err)
|
||||
}
|
||||
got, err := VerifyOIDCState(state)
|
||||
if err != nil {
|
||||
t.Fatalf("VerifyOIDCState: %v", err)
|
||||
}
|
||||
if got.Nonce != "nonce-abc" || got.RedirectURI != "http://localhost:5173/login" {
|
||||
t.Fatalf("unexpected payload: %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerifyOIDCStateRejectsTamperedPayload(t *testing.T) {
|
||||
t.Setenv("JWT_SECRET", "test-oidc-state-secret")
|
||||
oidcStateSecretOnce = sync.Once{}
|
||||
oidcStateSecret = ""
|
||||
|
||||
state, err := SignOIDCState(&OIDCStatePayload{
|
||||
Nonce: "nonce-abc",
|
||||
RedirectURI: "http://localhost:5173/login",
|
||||
IssuedAt: time.Now().Unix(),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("SignOIDCState: %v", err)
|
||||
}
|
||||
parts := strings.Split(state, ".")
|
||||
tampered := parts[0] + ".AAAA"
|
||||
if _, err := VerifyOIDCState(tampered); err == nil {
|
||||
t.Fatal("expected tampered state to be rejected")
|
||||
}
|
||||
}
|
||||
@@ -754,6 +754,24 @@ func DefaultSSRFSafeHTTPClientConfig() SSRFSafeHTTPClientConfig {
|
||||
// ErrSSRFRedirectBlocked is returned when a redirect target is blocked due to SSRF protection
|
||||
var ErrSSRFRedirectBlocked = fmt.Errorf("redirect blocked: target URL failed SSRF validation")
|
||||
|
||||
// sameHTTPOrigin reports whether two URLs share scheme and host (port-aware).
|
||||
func sameHTTPOrigin(a, b *url.URL) bool {
|
||||
if a == nil || b == nil {
|
||||
return false
|
||||
}
|
||||
return strings.EqualFold(a.Scheme, b.Scheme) && strings.EqualFold(a.Host, b.Host)
|
||||
}
|
||||
|
||||
// stripRedirectSensitiveHeaders removes credentials that must not follow a
|
||||
// cross-host redirect (Go only strips Authorization/Cookie by default).
|
||||
func stripRedirectSensitiveHeaders(req *http.Request) {
|
||||
req.Header.Del("Authorization")
|
||||
req.Header.Del("Cookie")
|
||||
req.Header.Del("X-Auth-Token")
|
||||
req.Header.Del("X-Api-Key")
|
||||
req.Header.Del("Api-Key")
|
||||
}
|
||||
|
||||
// NewSSRFSafeHTTPClient creates an HTTP client that validates redirect targets against SSRF protections.
|
||||
// This prevents SSRF attacks via HTTP redirects where an attacker's server redirects to internal services.
|
||||
func NewSSRFSafeHTTPClient(config SSRFSafeHTTPClientConfig) *http.Client {
|
||||
@@ -773,6 +791,12 @@ func NewSSRFSafeHTTPClient(config SSRFSafeHTTPClientConfig) *http.Client {
|
||||
return fmt.Errorf("stopped after %d redirects", config.MaxRedirects)
|
||||
}
|
||||
|
||||
// Strip credentials when the redirect crosses hosts so connector
|
||||
// tokens (e.g. Yuque X-Auth-Token) cannot leak to a third party.
|
||||
if len(via) > 0 && !sameHTTPOrigin(via[0].URL, req.URL) {
|
||||
stripRedirectSensitiveHeaders(req)
|
||||
}
|
||||
|
||||
// Validate the redirect target URL for SSRF (whitelist-aware).
|
||||
// Even whitelisted hosts must use http/https to prevent scheme-based attacks.
|
||||
redirectScheme := strings.ToLower(req.URL.Scheme)
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestSSRFSafeClientStripsAuthTokenOnCrossHostRedirect(t *testing.T) {
|
||||
t.Setenv("SSRF_WHITELIST", "127.0.0.1,::1,localhost")
|
||||
ResetSSRFWhitelistForTest()
|
||||
t.Cleanup(ResetSSRFWhitelistForTest)
|
||||
|
||||
var gotToken string
|
||||
attacker := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
gotToken = r.Header.Get("X-Auth-Token")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
defer attacker.Close()
|
||||
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/start", func(w http.ResponseWriter, r *http.Request) {
|
||||
http.Redirect(w, r, attacker.URL, http.StatusFound)
|
||||
})
|
||||
origin := httptest.NewServer(mux)
|
||||
defer origin.Close()
|
||||
|
||||
client := NewSSRFSafeHTTPClient(SSRFSafeHTTPClientConfig{
|
||||
Timeout: 5 * time.Second,
|
||||
MaxRedirects: 5,
|
||||
})
|
||||
req, err := http.NewRequest(http.MethodGet, origin.URL+"/start", nil)
|
||||
if err != nil {
|
||||
t.Fatalf("NewRequest: %v", err)
|
||||
}
|
||||
req.Header.Set("X-Auth-Token", "super-secret-yuque-token")
|
||||
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
t.Fatalf("Do: %v", err)
|
||||
}
|
||||
resp.Body.Close()
|
||||
|
||||
if gotToken != "" {
|
||||
t.Fatalf("X-Auth-Token leaked on cross-host redirect: %q", gotToken)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user