Debian Codegraph @

lib/3rdParty/composer/aws/aws-sdk-php/src/Signature/DpopSignature.php

raw symbols SCIP
1 <?php
2 namespace Aws\Signature;
3
4 use Psr\Http\Message\RequestInterface;
5 use Psr\Http\Message\UriInterface;
6 use Random\RandomException;
7
8 final class DpopSignature
9 {
10 public const ALLOW_LISTED_SERVICES = ['signin' => true];
11 private const EXT_OPENSSL = 'openssl';
12 private const CURVE_NAME = 'prime256v1';
13 private const HEADER_DPOP = 'DPop';
14 private const HEADER_TYP = 'dpop+jwt';
15 private const HEADER_ALG = 'ES256';
16 private const HEADER_JWK_KTY = 'EC';
17 private const HEADER_JWK_CRV = 'P-256';
18 private const PAYLOAD_HTM = 'POST';
19 private const JWK_SCHEMA = [
20 'kty' => self::HEADER_JWK_KTY,
21 'crv' => self::HEADER_JWK_CRV,
22 ];
23 private const HEADER_SCHEMA = [
24 'typ' => self::HEADER_TYP,
25 'alg' => self::HEADER_ALG,
26 'jwk' => self::JWK_SCHEMA
27 ];
28 private const PAYLOAD_SCHEMA = [
29 'htm' => self::PAYLOAD_HTM,
30 ];
31
32 /**
33 * Creates a new DpopSignature instance for the specified service
34 *
35 * @param string $serviceName The name of the AWS service (must be in the allow list)
36 *
37 * @throws \RuntimeException If the OpenSSL extension is not loaded
38 * @throws \InvalidArgumentException If the service is not in the allow list
39 */
40 public function __construct(string $serviceName)
41 {
42 if (!extension_loaded(self::EXT_OPENSSL)) {
43 throw new \RuntimeException(
44 'the `openssl` extension is required to generate DPop signatures. '
45 . 'Please install or enable the `openssl` extension.'
46 );
47 }
48
49 if (!isset(self::ALLOW_LISTED_SERVICES[$serviceName])) {
50 throw new \InvalidArgumentException(
51 "The '{$serviceName}' service does not support DPop signatures. "
52 . 'Please configure a signature version this service supports.'
53 );
54 }
55 }
56
57 /**
58 * Signs an HTTP request with a DPoP header
59 *
60 * @param RequestInterface $request The HTTP request to sign
61 * @param \OpenSSLAsymmetricKey $key The private key for signing
62 *
63 * @return RequestInterface The request with the DPoP header added
64 * @throws \RuntimeException|\Exception If signature generation fails
65 */
66 public function signRequest(
67 RequestInterface $request,
68 \OpenSSLAsymmetricKey $key,
69 ) {
70 $dpopHeaderValue = $this->generateDpopProof($key, $request->getUri());
71
72 return $request->withHeader(self::HEADER_DPOP, $dpopHeaderValue);
73 }
74
75 /**
76 * Generates the DPoP JWT header value for the request
77 *
78 * @param \OpenSSLAsymmetricKey $key The private key for signing
79 * @param UriInterface $uri The URI of the request
80 *
81 * @return string The complete DPoP JWT token
82 * @throws \RuntimeException|\Exception If signature generation fails
83 */
84 private function generateDpopProof(
85 \OpenSSLAsymmetricKey $key,
86 UriInterface $uri
87 ): string
88 {
89 $keyDetails = openssl_pkey_get_details($key);
90 if (($keyDetails['ec']['curve_name'] ?? '') !== self::CURVE_NAME) {
91 throw new \InvalidArgumentException(
92 'DPoP signature keys must use P-256 curve. '
93 . 'Please check your configuration and try again.'
94 );
95 }
96
97 ['x' => $x, 'y' => $y] = $keyDetails['ec'];
98 $header = $this->buildDpopHeader($x, $y);
99 $payload = $this->buildDpopPayload((string) $uri);
100
101 $message = $this->base64url_encode(json_encode($header))
102 . '.' . $this->base64url_encode(json_encode($payload));
103 $signature = '';
104 if (!openssl_sign($message, $signature, $key, OPENSSL_ALGO_SHA256)) {
105 $error = openssl_error_string();
106
107 throw new \RuntimeException(
108 'Failed to generate signature.' . ($error ? ": $error" : '.')
109 );
110 }
111
112 $signature = $this->derToRaw($signature);
113
114 return $message . '.' . $this->base64url_encode($signature);
115 }
116
117 /**
118 * Builds the DPoP JWT header with the public key coordinates
119 *
120 * @param string $x The x-coordinate of the EC public key
121 * @param string $y The y-coordinate of the EC public key
122 *
123 * @return array The complete DPoP header with JWK
124 */
125 private function buildDpopHeader(string $x, string $y): array
126 {
127 return array_merge_recursive(self::HEADER_SCHEMA, [
128 'jwk' => [
129 'x' => $this->base64url_encode($x),
130 'y' => $this->base64url_encode($y)
131 ]
132 ]);
133 }
134
135 /**
136 * Builds the DPoP JWT payload with request-specific claims
137 *
138 * @param string $uri The target URI for the HTTP request
139 *
140 * @return array The complete DPoP payload with jti, htm, htu, and iat claims
141 * @throws RandomException
142 */
143 private function buildDpopPayload(string $uri): array
144 {
145 return array_merge(self::PAYLOAD_SCHEMA, [
146 'jti' => $this->uuidv4(),
147 'htu' => $uri,
148 'iat' => time()
149 ]);
150 }
151
152 /**
153 * Generates a version 4 UUID
154 *
155 * @return string A UUID v4 string
156 * @throws RandomException
157 */
158 private function uuidv4(): string
159 {
160 $data = random_bytes(16);
161 $data[6] = chr(ord($data[6]) & 0x0f | 0x40);
162 $data[8] = chr(ord($data[8]) & 0x3f | 0x80);
163
164 return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
165 }
166
167 /**
168 * Encodes data to Base64URL format (RFC 4648)
169 *
170 * @param string $data The data to encode
171 *
172 * @return string Base64URL encoded string (no padding, URL-safe characters)
173 */
174 private function base64url_encode(string $data): string
175 {
176 return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
177 }
178
179 /**
180 * Convert DER-encoded ECDSA signature to raw R||S format (64 bytes for ES256)
181 *
182 * @param string $derSignature DER-encoded signature from openssl_sign
183 *
184 * @return string Raw signature (64 bytes: 32 bytes R + 32 bytes S)
185 * @throws \Exception If the DER signature is invalid
186 */
187 private function derToRaw(string $derSignature): string
188 {
189 $hex = bin2hex($derSignature);
190 $pos = 0;
191
192 // Parse SEQUENCE tag (0x30)
193 if (substr($hex, $pos, 2) !== '30') {
194 throw new \Exception('Invalid DER signature format: missing SEQUENCE tag');
195 }
196 $pos += 2;
197
198 // Parse SEQUENCE length
199 $seqLen = hexdec(substr($hex, $pos, 2));
200 $pos += 2;
201
202 // Parse first INTEGER tag (0x02) for R
203 if (substr($hex, $pos, 2) !== '02') {
204 throw new \Exception('Invalid DER signature format: missing R INTEGER tag');
205 }
206 $pos += 2;
207
208 // Parse R length
209 $rLen = hexdec(substr($hex, $pos, 2));
210 $pos += 2;
211
212 // Extract R value
213 $r = substr($hex, $pos, $rLen * 2);
214 if (strlen($r) !== $rLen * 2) {
215 throw new \Exception('Invalid DER signature: R length mismatch');
216 }
217 $pos += $rLen * 2;
218
219 // Parse second INTEGER tag (0x02) for S
220 if (substr($hex, $pos, 2) !== '02') {
221 throw new \Exception('Invalid DER signature format: missing S INTEGER tag');
222 }
223 $pos += 2;
224
225 // Parse S length
226 $sLen = hexdec(substr($hex, $pos, 2));
227 $pos += 2;
228
229 // Extract S value
230 $s = substr($hex, $pos, $sLen * 2);
231 if (strlen($s) !== $sLen * 2) {
232 throw new \Exception('Invalid DER signature: S length mismatch');
233 }
234
235 // Remove leading zeros (if any) and pad to 32 bytes
236 $r = str_pad(ltrim($r, '0'), 64, '0', STR_PAD_LEFT);
237 $s = str_pad(ltrim($s, '0'), 64, '0', STR_PAD_LEFT);
238
239 // Ensure exactly 32 bytes each
240 if (strlen($r) !== 64 || strlen($s) !== 64) {
241 throw new \Exception('Invalid signature component length');
242 }
243
244 return hex2bin($r . $s);
245 }
246 }