|
| 1 | +/* |
| 2 | + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"). |
| 5 | + * You may not use this file except in compliance with the License. |
| 6 | + * A copy of the License is located at |
| 7 | + * |
| 8 | + * http://aws.amazon.com/apache2.0 |
| 9 | + * |
| 10 | + * or in the "license" file accompanying this file. This file is distributed |
| 11 | + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either |
| 12 | + * express or implied. See the License for the specific language governing |
| 13 | + * permissions and limitations under the License. |
| 14 | + */ |
| 15 | + |
| 16 | +package software.amazon.awssdk.services.signin.internal; |
| 17 | + |
| 18 | +import java.io.ByteArrayOutputStream; |
| 19 | +import java.io.IOException; |
| 20 | +import java.nio.charset.StandardCharsets; |
| 21 | +import java.security.Signature; |
| 22 | +import java.security.interfaces.ECPrivateKey; |
| 23 | +import java.security.interfaces.ECPublicKey; |
| 24 | +import java.security.spec.ECPoint; |
| 25 | +import java.util.Arrays; |
| 26 | +import java.util.Base64; |
| 27 | +import software.amazon.awssdk.annotations.SdkInternalApi; |
| 28 | +import software.amazon.awssdk.thirdparty.jackson.core.JsonFactory; |
| 29 | +import software.amazon.awssdk.thirdparty.jackson.core.JsonGenerator; |
| 30 | +import software.amazon.awssdk.utils.Pair; |
| 31 | + |
| 32 | +/** |
| 33 | + * Utilities that implement rfc9449 - OAuth 2.0 Demonstrating Proof of Possession (DPoP) |
| 34 | +*/ |
| 35 | +@SdkInternalApi |
| 36 | +public final class DpopHeaderGenerator { |
| 37 | + |
| 38 | + public static final int ES256_SIGNATURE_BYTE_LENGTH = 64; |
| 39 | + public static final byte DER_SEQUENCE_TAG = 0x30; |
| 40 | + |
| 41 | + private DpopHeaderGenerator() {} |
| 42 | + |
| 43 | + /** |
| 44 | + * Construct a rfc9449 - OAuth 2.0 Demonstrating Proof of Possession (DPoP) header. |
| 45 | + * |
| 46 | + * The DPoP HTTP header must be a signed JWT (RFC 7519: JSON Web Token), which includes a |
| 47 | + * JWK (RFC 7517: JSON Web Key). |
| 48 | + * |
| 49 | + * For reference, see: |
| 50 | + * <ul> |
| 51 | + * <li><a href="https://datatracker.ietf.org/doc/html/rfc9449">RFC 9449 - |
| 52 | + * OAuth 2.0 Demonstrating Proof of Possession (DPoP)</a></li> |
| 53 | + * <li><a href="https://datatracker.ietf.org/doc/html/rfc7519">RFC 7519 - JSON Web Token (JWT)</a></li> |
| 54 | + * <li><a href="https://datatracker.ietf.org/doc/html/rfc7517">RFC 7517 - JSON Web Key (JWK)</a></li> |
| 55 | + * </ul> |
| 56 | + * |
| 57 | + * @param pemContent - EC1 / RFC 5915 ASN.1 formated PEM contents |
| 58 | + * @param endpoint - The HTTP target URI (Section 7.1 of [RFC9110]) of the request to which the JWT is attached, |
| 59 | + * without query and fragment parts |
| 60 | + * @param epochSeconds - creation time of the JWT in epoch seconds. |
| 61 | + * @param uuid - Unique identifier for the DPoP proof JWT - should be a UUID4 string. |
| 62 | + * @return DPoP header value |
| 63 | + * @throws Exception |
| 64 | + */ |
| 65 | + public static String generateDPoPProofHeader(String pemContent, String endpoint, long epochSeconds, String uuid) |
| 66 | + throws Exception { |
| 67 | + // Load EC public and private key from PEM |
| 68 | + Pair<ECPrivateKey, ECPublicKey> keys = EcKeyLoader.loadSec1Pem(pemContent); |
| 69 | + ECPrivateKey privateKey = keys.left(); |
| 70 | + ECPublicKey publicKey = keys.right(); |
| 71 | + |
| 72 | + // Build JSON strings (header, payload) with JsonGenerator |
| 73 | + String headerJson = buildHeaderJson(publicKey); |
| 74 | + String payloadJson = buildPayloadJson(uuid, endpoint, epochSeconds); |
| 75 | + |
| 76 | + // Base64URL encode header + payload |
| 77 | + String encodedHeader = base64UrlEncode(headerJson.getBytes(StandardCharsets.UTF_8)); |
| 78 | + String encodedPayload = base64UrlEncode(payloadJson.getBytes(StandardCharsets.UTF_8)); |
| 79 | + String message = encodedHeader + "." + encodedPayload; |
| 80 | + |
| 81 | + // Sign (ES256) |
| 82 | + Signature signature = Signature.getInstance("SHA256withECDSA"); |
| 83 | + signature.initSign(privateKey); |
| 84 | + signature.update(message.getBytes(StandardCharsets.UTF_8)); |
| 85 | + byte[] signatureBytes = translateDerSignatureToJws(signature.sign(), ES256_SIGNATURE_BYTE_LENGTH); |
| 86 | + |
| 87 | + // Combine into JWT |
| 88 | + String encodedSignature = base64UrlEncode(signatureBytes); |
| 89 | + return message + "." + encodedSignature; |
| 90 | + } |
| 91 | + |
| 92 | + // build the JWT header which includes the public key |
| 93 | + private static String buildHeaderJson(ECPublicKey publicKey) throws IOException { |
| 94 | + ECPoint pubPoint = publicKey.getW(); |
| 95 | + String x = base64UrlEncode(stripLeadingZero(pubPoint.getAffineX().toByteArray())); |
| 96 | + String y = base64UrlEncode(stripLeadingZero(pubPoint.getAffineY().toByteArray())); |
| 97 | + ByteArrayOutputStream out = new ByteArrayOutputStream(); |
| 98 | + JsonFactory factory = new JsonFactory(); |
| 99 | + try (JsonGenerator gen = factory.createGenerator(out)) { |
| 100 | + gen.writeStartObject(); |
| 101 | + gen.writeStringField("typ", "dpop+jwt"); |
| 102 | + gen.writeStringField("alg", "ES256"); |
| 103 | + |
| 104 | + gen.writeObjectFieldStart("jwk"); |
| 105 | + gen.writeStringField("crv", "P-256"); |
| 106 | + gen.writeStringField("kty", "EC"); |
| 107 | + gen.writeStringField("x", x); |
| 108 | + gen.writeStringField("y", y); |
| 109 | + gen.writeEndObject(); // end jwk |
| 110 | + gen.writeEndObject(); // end root |
| 111 | + } |
| 112 | + return out.toString(); |
| 113 | + } |
| 114 | + |
| 115 | + private static String buildPayloadJson(String uuid, String endpoint, long epochSeconds) throws IOException { |
| 116 | + ByteArrayOutputStream out = new ByteArrayOutputStream(); |
| 117 | + JsonFactory factory = new JsonFactory(); |
| 118 | + try (JsonGenerator gen = factory.createGenerator(out)) { |
| 119 | + gen.writeStartObject(); |
| 120 | + gen.writeStringField("jti", uuid); |
| 121 | + gen.writeStringField("htm", "POST"); |
| 122 | + gen.writeStringField("htu", endpoint); |
| 123 | + gen.writeNumberField("iat", epochSeconds); |
| 124 | + gen.writeEndObject(); |
| 125 | + } |
| 126 | + return out.toString(); |
| 127 | + } |
| 128 | + |
| 129 | + /** |
| 130 | + * Java Signature from SHA256withECDSA produces an ASN.1/DER encoded signature. |
| 131 | + * This method translates that signature into the concatenated (R,S) format expected by JWS. |
| 132 | + * |
| 133 | + * An ECDSA signature always produces two big integers: R and S. The DER format encodes these in a variable |
| 134 | + * length sequence because the values are encoded without leading zeroes with a structure following: |
| 135 | + * [ SEQUENCE_TAG, total_length, INTEGER_TAG, length of R, (bytes of R), INTEGER_TAG, length OF S, ( bytes of S) ] |
| 136 | + * |
| 137 | + * The JWT/JOSE spec defines ECDSA signatures as two 32 byte, big-endian integer values for R and S (total of 64 bytes): |
| 138 | + * [ 32 bytes of R, 32 bytes of S] |
| 139 | + * |
| 140 | + * @param derSignature The ASN1/DER-encoded signature. |
| 141 | + * @param outputLength The expected length of the ECDSA JWS signature. This should be 64 for ES256 |
| 142 | + * |
| 143 | + * @return The ECDSA JWS encoded signature (concatenated r,s values) |
| 144 | + **/ |
| 145 | + private static byte[] translateDerSignatureToJws(byte[] derSignature, int outputLength) |
| 146 | + throws Exception { |
| 147 | + |
| 148 | + // validate DER signature format |
| 149 | + if (derSignature.length < 8 || derSignature[0] != DER_SEQUENCE_TAG) { |
| 150 | + throw new RuntimeException("Invalid ECDSA signature format"); |
| 151 | + } |
| 152 | + |
| 153 | + // the total length may be more than 1 byte |
| 154 | + // if the first byte is (0x81), its 2 bytes |
| 155 | + int offset; // point to the start of the first INTEGER_TAG |
| 156 | + if (derSignature[1] > 0) { |
| 157 | + offset = 2; |
| 158 | + } else if (derSignature[1] == (byte) 0x81) { |
| 159 | + offset = 3; |
| 160 | + } else { |
| 161 | + throw new RuntimeException("Invalid ECDSA signature format"); |
| 162 | + } |
| 163 | + |
| 164 | + // get the length of R as the byte after the first INTEGER_TAG |
| 165 | + byte rLength = derSignature[offset + 1]; |
| 166 | + |
| 167 | + // determine the number of significant (non-zero) bytes in R |
| 168 | + int i; |
| 169 | + int endOfR = offset + 2 + rLength; |
| 170 | + for (i = rLength; (i > 0) && (derSignature[endOfR - i] == 0); i--) { |
| 171 | + // do nothing |
| 172 | + } |
| 173 | + |
| 174 | + // get the length of S as the byte after the second INTEGER_TAG which is: |
| 175 | + byte sLength = derSignature[endOfR + 1]; |
| 176 | + |
| 177 | + // determine number of significant bytes in S |
| 178 | + int j; |
| 179 | + int endOfS = endOfR + 2 + sLength; |
| 180 | + for (j = sLength; (j > 0) && (derSignature[endOfS - j] == 0); j--) { |
| 181 | + // do nothing |
| 182 | + } |
| 183 | + |
| 184 | + int rawLen = Math.max(i, j); |
| 185 | + rawLen = Math.max(rawLen, outputLength / 2); |
| 186 | + |
| 187 | + // sanity check, ensure the internal structure matches the DER spec. |
| 188 | + if ((derSignature[offset - 1] & 0xff) != derSignature.length - offset |
| 189 | + || (derSignature[offset - 1] & 0xff) != 2 + rLength + 2 + sLength |
| 190 | + || derSignature[offset] != 2 |
| 191 | + || derSignature[endOfR] != 2) { |
| 192 | + throw new RuntimeException("Invalid ECDSA signature format"); |
| 193 | + } |
| 194 | + |
| 195 | + final byte[] jwsSignature = new byte[2 * rawLen]; |
| 196 | + // copy the significant bytes of R (i bytes), removing any leading zeros, into the first half of output array. |
| 197 | + // Right aligned! |
| 198 | + System.arraycopy(derSignature, endOfR - i, jwsSignature, rawLen - i, i); |
| 199 | + // do the same for S to the second half of the output array. Also right aligned. |
| 200 | + System.arraycopy(derSignature, (offset + 2 + rLength + 2 + sLength) - j, jwsSignature, 2 * rawLen - j, j); |
| 201 | + |
| 202 | + return jwsSignature; |
| 203 | + } |
| 204 | + |
| 205 | + private static String base64UrlEncode(byte[] data) { |
| 206 | + return Base64.getUrlEncoder().withoutPadding().encodeToString(data); |
| 207 | + } |
| 208 | + |
| 209 | + private static byte[] stripLeadingZero(byte[] bytes) { |
| 210 | + if (bytes.length > 1 && bytes[0] == 0x00) { |
| 211 | + return Arrays.copyOfRange(bytes, 1, bytes.length); |
| 212 | + } |
| 213 | + return bytes; |
| 214 | + } |
| 215 | + |
| 216 | + public static void main(String[] args) throws Exception { |
| 217 | + String pem = "-----BEGIN EC PRIVATE KEY-----\n" |
| 218 | + + "MHcCAQEEICeY73qhQO/3o1QnrL5Nu3HMDB9h3kVW6imRdcHks0tboAoGCCqGSM49" |
| 219 | + + "AwEHoUQDQgAEbefyxjd/UlGwAPF6hy0k4yCW7dSghc6yPd4To0sBqX0tPS/aoLrl" |
| 220 | + + "QnPjfDslgD29p4+Pgwxj1s8cFHVeDKdKTQ==\n" |
| 221 | + + "-----END EC PRIVATE KEY-----"; |
| 222 | + String dpopHeader = DpopHeaderGenerator.generateDPoPProofHeader( |
| 223 | + pem, "https://ap-northeast-1.aws-signin-testing.amazon.com/v1/token", |
| 224 | + 1760727856, |
| 225 | + "c7cf0359-f736-4a55-bbc1-70f6a0e2d55d" |
| 226 | + ); |
| 227 | + |
| 228 | + System.out.println("\n\nDPOP Proof header:\n" + dpopHeader); |
| 229 | + } |
| 230 | +} |
0 commit comments