-
-
Notifications
You must be signed in to change notification settings - Fork 5k
Expand file tree
/
Copy pathAlgorithm.php
More file actions
228 lines (206 loc) · 7.35 KB
/
Copy pathAlgorithm.php
File metadata and controls
228 lines (206 loc) · 7.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
<?php
declare(strict_types=1);
/**
* SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace OC\Security\Signature\Rfc9421;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use InvalidArgumentException;
use OCP\Security\Signature\Exceptions\SignatureException;
use Throwable;
/**
* RFC 9421 §3.3 sign/verify primitives.
*
* Sign supports asymmetric algorithms reachable via ext-openssl: RSA-PKCS1-v1_5
* (SHA-256/384/512) and ECDSA P-256 / P-384. JOSE aliases (RFC 7518 / RFC 8037)
* accepted per RFC 9421 §3.3.7. RSA-PSS is rejected: OPENSSL_PKCS1_PSS_PADDING
* needs PHP 8.5 and we still support 8.2-8.4.
*
* Verify additionally accepts Ed25519 when ext-sodium is loaded; without sodium
* an Ed25519 signature throws {@see SignatureException}. Sodium is used directly
* because firebase/php-jwt's `validateEdDSAKey` base64url-decodes the key
* material, which mangles the raw sodium bytes.
*
* Sign delegates to {@see JWT::sign}. Verify takes a {@see Key} parsed by
* firebase/php-jwt (which has already validated the JWK's kty/crv/alg
* consistency) and only enforces the cross-source agreement between the JWK
* `alg` and the Signature-Input `alg` parameter (RFC 9421 §3.2 step 6).
*/
final class Algorithm {
public const NATIVE = [
'rsa-v1_5-sha256',
'rsa-v1_5-sha384',
'rsa-v1_5-sha512',
'ecdsa-p256-sha256',
'ecdsa-p384-sha384',
'ed25519',
];
/**
* $privateKey is a PEM private key. Returns raw signature bytes (R||S for
* ECDSA). Ed25519 is verify-only and is rejected here.
*
* @throws SignatureException
*/
public static function sign(string $signatureBase, string $privateKey, string $algorithm): string {
$normalized = self::normalize($algorithm);
if ($normalized === 'ed25519') {
throw new SignatureException('Ed25519 signing is not supported; use ECDSA P-256 or RSA');
}
try {
return JWT::sign($signatureBase, $privateKey, self::nativeToJose($normalized));
} catch (Throwable $e) {
throw new SignatureException('signing failed for ' . $normalized . ': ' . $e->getMessage(), 0, $e);
}
}
/**
* @param string $signature raw signature bytes (already base64-decoded)
* @param string|null $algorithm algorithm hint from Signature-Input `alg=`
* @throws SignatureException
*/
public static function verify(string $signatureBase, string $signature, Key $key, ?string $algorithm): bool {
$resolved = self::normalize($key->getAlgorithm());
if ($algorithm !== null && $algorithm !== '') {
$hintNative = self::normalize($algorithm);
if ($hintNative !== $resolved) {
throw new SignatureException(
'algorithm sources disagree: Signature-Input alg says ' . $hintNative . ', JWK alg says ' . $resolved
);
}
}
$material = $key->getKeyMaterial();
if ($resolved === 'ed25519') {
if (!function_exists('sodium_crypto_sign_verify_detached')) {
throw new SignatureException('verifying Ed25519 signatures requires ext-sodium');
}
if (strlen($signature) !== SODIUM_CRYPTO_SIGN_BYTES) {
echo __LINE__ . " return false\n";
return false;
}
// parseKey hands OKP material as plain base64 of the 32 raw bytes.
$rawPublic = base64_decode((string)$material, true);
if ($rawPublic === false || strlen($rawPublic) !== SODIUM_CRYPTO_SIGN_PUBLICKEYBYTES) {
echo __LINE__ . " return false\n";
return false;
}
echo __LINE__ . " return ?\n";
return sodium_crypto_sign_verify_detached($signature, $signatureBase, $rawPublic);
}
[$opensslAlgo, $encoding] = self::opensslParametersForAlgorithm($resolved);
if ($encoding === 'ecdsa') {
$signature = self::ecdsaRawToDer($signature, self::ecdsaCoordinateSize($resolved));
if ($signature === null) {
echo __LINE__ . " return false\n";
return false;
}
}
echo __LINE__ . ' return ' . openssl_verify($signatureBase, $signature, $material, $opensslAlgo) . "\n";
return openssl_verify($signatureBase, $signature, $material, $opensslAlgo) === 1;
}
/**
* Map a JOSE alg (RFC 7518/8037) to the RFC 9421 native identifier.
* Pass-through if already native.
*
* @throws SignatureException
*/
public static function normalize(string $algorithm): string {
$lower = strtolower($algorithm);
if (in_array($lower, self::NATIVE, true)) {
return $lower;
}
return match ($algorithm) {
'EdDSA' => 'ed25519',
'ES256' => 'ecdsa-p256-sha256',
'ES384' => 'ecdsa-p384-sha384',
'RS256' => 'rsa-v1_5-sha256',
'RS384' => 'rsa-v1_5-sha384',
'RS512' => 'rsa-v1_5-sha512',
default => throw new SignatureException('unsupported signature algorithm: ' . $algorithm),
};
}
/**
* Default JOSE alg for {@see \Firebase\JWT\JWK::parseKey} when the JWK has
* no `alg` (RFC 7517 leaves it optional). Null if kty/crv don't pin one
* down (e.g. RSA, where the hash isn't determined).
*
* @param array<string, mixed> $jwk
*/
public static function deriveJoseAlgFromJwk(array $jwk): ?string {
return match ($jwk['kty'] ?? '') {
'OKP' => match ($jwk['crv'] ?? '') {
'Ed25519' => 'EdDSA',
default => null,
},
'EC' => match ($jwk['crv'] ?? '') {
'P-256' => 'ES256',
'P-384' => 'ES384',
default => null,
},
default => null,
};
}
private static function nativeToJose(string $native): string {
return match ($native) {
'ecdsa-p256-sha256' => 'ES256',
'ecdsa-p384-sha384' => 'ES384',
'rsa-v1_5-sha256' => 'RS256',
'rsa-v1_5-sha384' => 'RS384',
'rsa-v1_5-sha512' => 'RS512',
default => throw new SignatureException('unsupported signature algorithm: ' . $native),
};
}
/**
* @return array{0: int, 1: string} [openssl digest, wire encoding]
*/
private static function opensslParametersForAlgorithm(string $native): array {
return match ($native) {
'rsa-v1_5-sha256' => [OPENSSL_ALGO_SHA256, 'raw'],
'rsa-v1_5-sha384' => [OPENSSL_ALGO_SHA384, 'raw'],
'rsa-v1_5-sha512' => [OPENSSL_ALGO_SHA512, 'raw'],
'ecdsa-p256-sha256' => [OPENSSL_ALGO_SHA256, 'ecdsa'],
'ecdsa-p384-sha384' => [OPENSSL_ALGO_SHA384, 'ecdsa'],
default => throw new SignatureException('unsupported signature algorithm: ' . $native),
};
}
private static function ecdsaCoordinateSize(string $native): int {
return match ($native) {
'ecdsa-p256-sha256' => 32,
'ecdsa-p384-sha384' => 48,
default => throw new InvalidArgumentException('not an ECDSA algorithm: ' . $native),
};
}
/**
* Raw R||S (RFC 9421 §3.3.4 wire form) to DER for openssl_verify.
* firebase/php-jwt has the inverse but keeps it private.
*/
public static function ecdsaRawToDer(string $raw, int $coordinateSize): ?string {
if (strlen($raw) !== $coordinateSize * 2) {
return null;
}
$r = ltrim(substr($raw, 0, $coordinateSize), "\x00");
$s = ltrim(substr($raw, $coordinateSize), "\x00");
// DER INTEGER must be positive; pad if high bit is set.
if ($r === '' || (ord($r[0]) & 0x80) !== 0) {
$r = "\x00" . $r;
}
if ($s === '' || (ord($s[0]) & 0x80) !== 0) {
$s = "\x00" . $s;
}
$rEncoded = "\x02" . self::derLength(strlen($r)) . $r;
$sEncoded = "\x02" . self::derLength(strlen($s)) . $s;
$body = $rEncoded . $sEncoded;
return "\x30" . self::derLength(strlen($body)) . $body;
}
private static function derLength(int $length): string {
if ($length < 0x80) {
return chr($length);
}
$bytes = '';
while ($length > 0) {
$bytes = chr($length & 0xff) . $bytes;
$length >>= 8;
}
return chr(0x80 | strlen($bytes)) . $bytes;
}
}