001/*
002 * Copyright 2026 Revetware LLC.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016package com.revetsec.saml;
017
018import com.revetsec.internal.encoding.EncodingException;
019import com.revetsec.internal.encoding.StrictUtf8;
020
021import com.revetsec.internal.crypto.EcCurve;
022import com.revetsec.internal.crypto.EcdsaSignatures;
023import org.jspecify.annotations.NonNull;
024import org.jspecify.annotations.Nullable;
025import javax.annotation.concurrent.Immutable;
026import java.io.ByteArrayOutputStream;
027import java.nio.charset.StandardCharsets;
028import java.security.GeneralSecurityException;
029import java.security.PublicKey;
030import java.security.Signature;
031import java.security.interfaces.ECPublicKey;
032import java.util.Arrays;
033import java.util.Base64;
034import java.util.HashMap;
035import java.util.List;
036import java.util.Map;
037import java.util.Objects;
038import java.util.Optional;
039import java.util.zip.DataFormatException;
040import java.util.zip.Inflater;
041
042/**
043 * A raw-octet HTTP-Redirect binding message. It retains the exact received signing input and
044 * does not release identity until the SP verifies the signature and SAML fields.
045 *
046 * @since 1.0.0
047 */
048@Immutable
049public final class SamlRedirectBindingMessage {
050    private final @NonNull Kind kind;
051    private final byte @NonNull [] xml;
052    private final @Nullable String relayState;
053    private final @NonNull String signedQuery;
054    private final @NonNull String algorithm;
055    private final byte @NonNull [] signature;
056
057    private SamlRedirectBindingMessage(@NonNull Kind kind, byte @NonNull [] xml,
058            @Nullable String relayState, @NonNull String signedQuery,
059            @NonNull String algorithm, byte @NonNull [] signature) {
060        this.kind = kind;
061        this.xml = xml.clone();
062        this.relayState = relayState;
063        this.signedQuery = signedQuery;
064        this.algorithm = algorithm;
065        this.signature = signature.clone();
066    }
067
068    /**
069     * Parses one raw query string before servlet or framework parameter decoding.
070     *
071     * @param rawQuery exact ASCII query octets represented as a String, without the leading ?
072     * @return parsed message or fixed rejection
073     * @since 1.0.0
074     */
075    public static @NonNull SamlRedirectBindingParseResult fromRawQueryResult(@NonNull String rawQuery) {
076        Objects.requireNonNull(rawQuery);
077        if (rawQuery.isEmpty() || rawQuery.length() > 65536) return SamlRedirectBindingParseResult.Rejected.INSTANCE;
078        Map<String, String> fields = new HashMap<>();
079        for (String field : rawQuery.split("&", -1)) {
080            int equals = field.indexOf('=');
081            if (equals < 1 || equals == field.length() - 1) return SamlRedirectBindingParseResult.Rejected.INSTANCE;
082            String name = field.substring(0, equals);
083            if (!List.of("SAMLRequest", "SAMLResponse", "RelayState", "SigAlg", "Signature").contains(name)
084                    || fields.putIfAbsent(name, field.substring(equals + 1)) != null)
085                return SamlRedirectBindingParseResult.Rejected.INSTANCE;
086        }
087        boolean request = fields.containsKey("SAMLRequest");
088        if (request == fields.containsKey("SAMLResponse") || !fields.containsKey("SigAlg")
089                || !fields.containsKey("Signature")) return SamlRedirectBindingParseResult.Rejected.INSTANCE;
090        String messageName = request ? "SAMLRequest" : "SAMLResponse";
091        byte[] message = percent(fields.get(messageName), 32768);
092        byte[] alg = percent(fields.get("SigAlg"), 256);
093        byte[] signed = percent(fields.get("Signature"), 8192);
094        byte[] relayBytes = fields.containsKey("RelayState") ? percent(fields.get("RelayState"), 80) : null;
095        if (message == null || alg == null || signed == null
096                || (fields.containsKey("RelayState") && relayBytes == null))
097            return SamlRedirectBindingParseResult.Rejected.INSTANCE;
098        String algorithm = ascii(alg);
099        String encoded = ascii(message);
100        String signatureEncoded = ascii(signed);
101        String relay = relayBytes == null ? null : relay(relayBytes);
102        if (algorithm == null || encoded == null || signatureEncoded == null
103                || (relayBytes != null && relay == null))
104            return SamlRedirectBindingParseResult.Rejected.INSTANCE;
105        byte[] compressed;
106        byte[] signature;
107        try {
108            compressed = Base64.getDecoder().decode(encoded);
109            signature = Base64.getDecoder().decode(signatureEncoded);
110        } catch (IllegalArgumentException exception) { return SamlRedirectBindingParseResult.Rejected.INSTANCE; }
111        if (compressed.length > 24576 || signature.length < 64 || signature.length > 1024)
112            return SamlRedirectBindingParseResult.Rejected.INSTANCE;
113        byte[] xml = inflate(compressed);
114        if (xml == null) return SamlRedirectBindingParseResult.Rejected.INSTANCE;
115        String signingInput = messageName + "=" + fields.get(messageName)
116                + (relay == null ? "" : "&RelayState=" + fields.get("RelayState"))
117                + "&SigAlg=" + fields.get("SigAlg");
118        return new SamlRedirectBindingParseResult.Parsed(new SamlRedirectBindingMessage(
119                request ? Kind.REQUEST : Kind.RESPONSE, xml, relay, signingInput, algorithm, signature));
120    }
121
122    /**
123     * Reports which SAML protocol message field was present.
124     *
125     * @return message kind
126     * @since 1.0.0
127     */
128    public @NonNull Kind getKind() { return kind; }
129    /**
130     * Returns the optional RelayState handle.
131     *
132     * @return optional handle
133     * @since 1.0.0
134     */
135    public @NonNull Optional<@NonNull String> getRelayState() { return Optional.ofNullable(relayState); }
136    byte @NonNull [] xml() { return xml.clone(); }
137    @Nullable String relayState() { return relayState; }
138
139    boolean verify(@NonNull List<@NonNull PublicKey> keys) {
140        return verify(keys, false);
141    }
142
143    boolean verify(@NonNull List<@NonNull PublicKey> keys, boolean allowSha1) {
144        String jca = switch (algorithm) {
145            case "http://www.w3.org/2000/09/xmldsig#rsa-sha1" -> allowSha1 ? "SHA1withRSA" : "";
146            case "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256" -> "SHA256withRSA";
147            case "http://www.w3.org/2001/04/xmldsig-more#rsa-sha384" -> "SHA384withRSA";
148            case "http://www.w3.org/2001/04/xmldsig-more#rsa-sha512" -> "SHA512withRSA";
149            case "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha256" -> "SHA256withECDSA";
150            case "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha384" -> "SHA384withECDSA";
151            case "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha512" -> "SHA512withECDSA";
152            default -> "";
153        };
154        if (jca.isEmpty()) return false;
155        for (PublicKey key : keys) {
156            try {
157                byte[] signatureBytes = signature;
158                if (jca.contains("ECDSA")) {
159                    if (!(key instanceof ECPublicKey ec)) continue;
160                    EcCurve curve = EcCurve.findByParameterSpec(ec.getParams()).orElse(null);
161                    if (curve == null) continue;
162                    signatureBytes = canonicalEcdsaSignature(signature, curve);
163                    if (signatureBytes == null) continue;
164                }
165                Signature verifier = Signature.getInstance(jca);
166                verifier.initVerify(key);
167                verifier.update(signedQuery.getBytes(StandardCharsets.US_ASCII));
168                if (verifier.verify(signatureBytes)) return true;
169            } catch (GeneralSecurityException exception) {
170                // Continue across configured rollover keys.
171            }
172        }
173        return false;
174    }
175
176    static byte @Nullable [] canonicalEcdsaSignature(byte @NonNull [] value,
177            @NonNull EcCurve curve) {
178        if (value.length == curve.getSignatureLength()) {
179            if (EcdsaSignatures.findShapeFailure(curve, value).isPresent()) return null;
180            return EcdsaSignatures.toDer(curve, value);
181        }
182        int position = 0;
183        if (value.length < 8 || value[position++] != 0x30) return null;
184        int length = value[position++] & 0xff;
185        if (length == 0x81) {
186            if (position >= value.length || (length = value[position++] & 0xff) < 128) return null;
187        } else if (length >= 128) return null;
188        if (position + length != value.length) return null;
189        byte[] raw = new byte[curve.getSignatureLength()];
190        for (int half = 0; half < 2; half++) {
191            if (position + 2 > value.length || value[position++] != 0x02) return null;
192            int integerLength = value[position++] & 0xff;
193            if (integerLength < 1 || integerLength > curve.getCoordinateLength() + 1
194                    || position + integerLength > value.length) return null;
195            int start = position;
196            if (value[start] == 0) {
197                if (integerLength == 1 || (value[start + 1] & 0x80) == 0) return null;
198                start++;
199            } else if ((value[start] & 0x80) != 0) return null;
200            int magnitudeLength = position + integerLength - start;
201            if (magnitudeLength > curve.getCoordinateLength()) return null;
202            System.arraycopy(value, start, raw,
203                    half * curve.getCoordinateLength() + curve.getCoordinateLength() - magnitudeLength,
204                    magnitudeLength);
205            position += integerLength;
206        }
207        if (position != value.length || EcdsaSignatures.findShapeFailure(curve, raw).isPresent())
208            return null;
209        byte[] canonical = EcdsaSignatures.toDer(curve, raw);
210        return Arrays.equals(canonical, value) ? canonical : null;
211    }
212
213    private static byte @Nullable [] inflate(byte @NonNull [] compressed) {
214        Inflater inflater = new Inflater(true);
215        try {
216            inflater.setInput(compressed);
217            ByteArrayOutputStream output = new ByteArrayOutputStream();
218            byte[] chunk = new byte[4096];
219            while (!inflater.finished()) {
220                if (output.size() >= 131072) return null;
221                int count = inflater.inflate(chunk, 0, Math.min(chunk.length, 131072 - output.size()));
222                if (count == 0) return null;
223                output.write(chunk, 0, count);
224            }
225            return inflater.getRemaining() == 0 ? output.toByteArray() : null;
226        } catch (DataFormatException exception) { return null; }
227        finally { inflater.end(); }
228    }
229
230    private static byte @Nullable [] percent(@Nullable String input, int maximum) {
231        if (input == null || input.length() > maximum * 3) return null;
232        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
233        for (int i = 0; i < input.length(); i++) {
234            char current = input.charAt(i);
235            if (current == '%') {
236                if (i + 2 >= input.length()) return null;
237                int high = asciiHex(input.charAt(++i));
238                int low = asciiHex(input.charAt(++i));
239                if (high < 0 || low < 0) return null;
240                bytes.write((high << 4) | low);
241            } else if (current >= 33 && current <= 126) bytes.write(current);
242            else return null;
243            if (bytes.size() > maximum) return null;
244        }
245        return bytes.toByteArray();
246    }
247
248    private static int asciiHex(char value) {
249        if (value >= '0' && value <= '9') return value - '0';
250        if (value >= 'A' && value <= 'F') return value - 'A' + 10;
251        if (value >= 'a' && value <= 'f') return value - 'a' + 10;
252        return -1;
253    }
254
255    private static @Nullable String ascii(byte @NonNull [] value) {
256        for (byte octet : value) if (octet < 33 || octet > 126) return null;
257        return new String(value, StandardCharsets.US_ASCII);
258    }
259
260    private static @Nullable String relay(byte @NonNull [] value) {
261        try {
262            String decoded = StrictUtf8.decode(value);
263            for (int index = 0; index < decoded.length(); index++) {
264                char character = decoded.charAt(index);
265                if (Character.isISOControl(character) || Character.isWhitespace(character)) return null;
266            }
267            return decoded;
268        } catch (EncodingException exception) { return null; }
269    }
270
271    /**
272     * HTTP-Redirect message field kind.
273     *
274     * @since 1.0.0
275     */
276    @Immutable
277    public enum Kind {
278        /** SAMLRequest. */ REQUEST,
279        /** SAMLResponse. */ RESPONSE
280    }
281
282    /**
283     * Redacts query and XML contents.
284     *
285     * @return redacted description
286     * @since 1.0.0
287     */
288    @Override public @NonNull String toString() { return "SamlRedirectBindingMessage{<redacted>}"; }
289}