fix(auth): handle saml logout and xml encryption padding

This commit is contained in:
mac
2026-07-17 09:42:12 +08:00
parent 157f0c65cb
commit b151356045
7 changed files with 112 additions and 12 deletions
+1
View File
@@ -18,5 +18,6 @@ JWT_TTL_MINUTES=120
SAML_ENTITY_ID=http://localhost:8080/api/v1/saml/metadata
SAML_ACS_URL=http://localhost:8080/api/v1/saml/acs
SAML_IDP_METADATA_URL=http://sso-internal.dev.qiniu.io/saml2/meta
SAML_LOGOUT_URL=http://sso-internal.dev.qiniu.io/signout
SAML_SP_CERT_FILE=certs/sp.crt
SAML_SP_KEY_FILE=certs/sp.key
+2
View File
@@ -28,6 +28,7 @@ type Config struct {
SAMLSPCert string
SAMLSPKey string
SAMLIDPMetaURL string
SAMLLogoutURL string
WayenLoginURL string
WayenTargetURL string
WayenUsernameKey string
@@ -78,6 +79,7 @@ func Load() Config {
SAMLSPCert: env("SAML_SP_CERT_FILE", "certs/sp.crt"),
SAMLSPKey: env("SAML_SP_KEY_FILE", "certs/sp.key"),
SAMLIDPMetaURL: env("SAML_IDP_METADATA_URL", "http://sso-internal.dev.qiniu.io/saml2/meta"),
SAMLLogoutURL: trimURL(env("SAML_LOGOUT_URL", "")),
WayenLoginURL: env("WAYEN_LOGIN_URL", ""),
WayenTargetURL: env("WAYEN_TARGET_URL", ""),
WayenUsernameKey: env("WAYEN_USERNAME_KEY", "email"),
+21 -1
View File
@@ -75,7 +75,10 @@ func (h *SAMLHandler) Logout(c *gin.Context) {
Expires: expired,
})
}
c.JSON(http.StatusOK, gin.H{"ok": true})
c.JSON(http.StatusOK, gin.H{
"ok": true,
"logout_url": h.logoutURL(),
})
}
func (h *SAMLHandler) ACS(c *gin.Context) {
@@ -125,3 +128,20 @@ func ssoRedirectURL(relayState, token string) string {
parsed.RawQuery = values.Encode()
return parsed.String()
}
func (h *SAMLHandler) logoutURL() string {
logoutURL := strings.TrimSpace(h.cfg.SAMLLogoutURL)
if logoutURL == "" {
return ""
}
parsed, err := url.Parse(logoutURL)
if err != nil {
return logoutURL
}
values := parsed.Query()
if values.Get("redirect") == "" {
values.Set("redirect", strings.TrimRight(h.cfg.PublicBaseURL, "/")+"/")
parsed.RawQuery = values.Encode()
}
return parsed.String()
}
+2 -7
View File
@@ -246,7 +246,7 @@ func decryptAESCBC(value, key []byte) ([]byte, error) {
cipherText := value[block.BlockSize():]
plain := make([]byte, len(cipherText))
cipher.NewCBCDecrypter(block, iv).CryptBlocks(plain, cipherText)
plain, err = pkcs7Unpad(plain, block.BlockSize())
plain, err = xmlEncCBCUnpad(plain, block.BlockSize())
if err != nil {
return nil, err
}
@@ -274,7 +274,7 @@ func decryptAESGCM(value, key []byte) ([]byte, error) {
return plain, nil
}
func pkcs7Unpad(value []byte, blockSize int) ([]byte, error) {
func xmlEncCBCUnpad(value []byte, blockSize int) ([]byte, error) {
if len(value) == 0 || len(value)%blockSize != 0 {
return nil, errors.New("invalid saml assertion padding length")
}
@@ -282,11 +282,6 @@ func pkcs7Unpad(value []byte, blockSize int) ([]byte, error) {
if padding == 0 || padding > blockSize || padding > len(value) {
return nil, errors.New("invalid saml assertion padding")
}
for _, b := range value[len(value)-padding:] {
if int(b) != padding {
return nil, errors.New("invalid saml assertion padding bytes")
}
}
return value[:len(value)-padding], nil
}
+69
View File
@@ -143,6 +143,47 @@ func TestDecodeSAMLResponseDecryptsEncryptedAssertion(t *testing.T) {
}
}
func TestDecodeSAMLResponseDecryptsEncryptedAssertionWithXMLCBCPadding(t *testing.T) {
t.Parallel()
key, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
t.Fatalf("generate key: %v", err)
}
keyFile := writeTestPrivateKey(t, key)
assertion := `<saml:Assertion xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion">
<saml:Subject><saml:NameID>carol@example.com</saml:NameID></saml:Subject>
</saml:Assertion>`
sessionKey := []byte("0123456789abcdef")
encryptedAssertion := encryptTestAssertionXMLCBCPadding(t, []byte(assertion), sessionKey)
encryptedKey, err := rsa.EncryptOAEP(sha1.New(), rand.Reader, &key.PublicKey, sessionKey, nil)
if err != nil {
t.Fatalf("encrypt key: %v", err)
}
response := `<samlp:Response xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol">
<saml:EncryptedAssertion xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion">
<xenc:EncryptedData xmlns:xenc="http://www.w3.org/2001/04/xmlenc#">
<xenc:EncryptionMethod Algorithm="` + xmlEncAES128CBC + `"></xenc:EncryptionMethod>
<ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
<xenc:EncryptedKey>
<xenc:CipherData><xenc:CipherValue>` + base64.StdEncoding.EncodeToString(encryptedKey) + `</xenc:CipherValue></xenc:CipherData>
</xenc:EncryptedKey>
</ds:KeyInfo>
<xenc:CipherData><xenc:CipherValue>` + base64.StdEncoding.EncodeToString(encryptedAssertion) + `</xenc:CipherValue></xenc:CipherData>
</xenc:EncryptedData>
</saml:EncryptedAssertion>
</samlp:Response>`
info, err := DecodeSAMLResponse(base64.StdEncoding.EncodeToString([]byte(response)), keyFile)
if err != nil {
t.Fatalf("DecodeSAMLResponse returned error: %v", err)
}
if info.NameID != "carol@example.com" {
t.Fatalf("unexpected name id: %q", info.NameID)
}
}
func TestDecodeSAMLResponseDecryptsGCMEncryptedAssertion(t *testing.T) {
t.Parallel()
@@ -221,6 +262,20 @@ func encryptTestAssertion(t *testing.T, plain, key []byte) []byte {
return out
}
func encryptTestAssertionXMLCBCPadding(t *testing.T, plain, key []byte) []byte {
t.Helper()
block, err := aes.NewCipher(key)
if err != nil {
t.Fatalf("init cipher: %v", err)
}
plain = xmlEncCBCPad(plain, block.BlockSize())
iv := bytes.Repeat([]byte{3}, block.BlockSize())
out := make([]byte, len(iv)+len(plain))
copy(out, iv)
cipher.NewCBCEncrypter(block, iv).CryptBlocks(out[len(iv):], plain)
return out
}
func encryptTestAssertionGCM(t *testing.T, plain, key []byte) []byte {
t.Helper()
block, err := aes.NewCipher(key)
@@ -244,6 +299,20 @@ func pkcs7Pad(value []byte, blockSize int) []byte {
return append(value, bytes.Repeat([]byte{byte(padding)}, padding)...)
}
func xmlEncCBCPad(value []byte, blockSize int) []byte {
padding := blockSize - len(value)%blockSize
if padding == 0 {
padding = blockSize
}
padded := make([]byte, len(value)+padding)
copy(padded, value)
for i := len(value); i < len(padded)-1; i++ {
padded[i] = byte(i % 251)
}
padded[len(padded)-1] = byte(padding)
return padded
}
func testIDPMetadataXML(entityID, redirectURL, postURL string) string {
return `<?xml version="1.0"?>
<EntityDescriptor xmlns="urn:oasis:names:tc:SAML:2.0:metadata" entityID="` + entityID + `">