PocketMine-MP 5.41.1 git-24c89e7eaf65eab6e3a56a4f03fced4c7154acc5
Loading...
Searching...
No Matches
JwtUtils.php
1<?php
2
3/*
4 *
5 * ____ _ _ __ __ _ __ __ ____
6 * | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \
7 * | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) |
8 * | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/
9 * |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_|
10 *
11 * This program is free software: you can redistribute it and/or modify
12 * it under the terms of the GNU Lesser General Public License as published by
13 * the Free Software Foundation, either version 3 of the License, or
14 * (at your option) any later version.
15 *
16 * @author PocketMine Team
17 * @link http://www.pocketmine.net/
18 *
19 *
20 */
21
22declare(strict_types=1);
23
24namespace pocketmine\network\mcpe;
25
26use pmmp\encoding\BE;
27use pmmp\encoding\Byte;
28use pmmp\encoding\ByteBufferReader;
31use function assert;
32use function base64_decode;
33use function base64_encode;
34use function bin2hex;
35use function chr;
36use function count;
37use function explode;
38use function hex2bin;
39use function is_array;
40use function json_decode;
41use function json_encode;
42use function json_last_error_msg;
43use function ltrim;
44use function openssl_error_string;
45use function openssl_pkey_get_details;
46use function openssl_pkey_get_public;
47use function openssl_sign;
48use function openssl_verify;
49use function ord;
50use function preg_match;
51use function rtrim;
52use function sprintf;
53use function str_pad;
54use function str_repeat;
55use function str_replace;
56use function str_split;
57use function strlen;
58use function strtr;
59use function substr;
60use const JSON_THROW_ON_ERROR;
61use const OPENSSL_ALGO_SHA256;
62use const OPENSSL_ALGO_SHA384;
63use const STR_PAD_LEFT;
64
65final class JwtUtils{
66 public const BEDROCK_SIGNING_KEY_CURVE_NAME = "secp384r1";
67
68 private const ASN1_INTEGER_TAG = "\x02";
69 private const ASN1_SEQUENCE_TAG = "\x30";
70
71 private const SIGNATURE_PART_LENGTH = 48;
72 private const SIGNATURE_ALGORITHM = OPENSSL_ALGO_SHA384;
73
79 public static function split(string $jwt) : array{
80 //limit of 4 allows us to detect too many parts without having to split the string up into a potentially large
81 //number of parts
82 $v = explode(".", $jwt, limit: 4);
83 if(count($v) !== 3){
84 throw new JwtException("Expected exactly 3 JWT parts delimited by a period");
85 }
86 return [$v[0], $v[1], $v[2]]; //workaround phpstan bug
87 }
88
97 public static function parse(string $token) : array{
98 $v = self::split($token);
99 $header = json_decode(self::b64UrlDecode($v[0]), true);
100 if(!is_array($header)){
101 throw new JwtException("Failed to decode JWT header JSON: " . json_last_error_msg());
102 }
103 $body = json_decode(self::b64UrlDecode($v[1]), true);
104 if(!is_array($body)){
105 throw new JwtException("Failed to decode JWT payload JSON: " . json_last_error_msg());
106 }
107 $signature = self::b64UrlDecode($v[2]);
108 return [$header, $body, $signature];
109 }
110
111 private static function signaturePartToAsn1(string $part) : string{
112 if(strlen($part) !== self::SIGNATURE_PART_LENGTH){
113 throw new JwtException("R and S for a SHA384 signature must each be exactly 48 bytes, but have " . strlen($part) . " bytes");
114 }
115 $part = ltrim($part, "\x00");
116 if(ord($part[0]) >= 128){
117 //ASN.1 integers with a leading 1 bit are considered negative - add a leading 0 byte to prevent this
118 //ECDSA signature R and S values are always positive
119 $part = "\x00" . $part;
120 }
121
122 //we can assume the length is 1 byte here - if it were larger than 127, more complex logic would be needed
123 assert(strlen($part) <= 127);
124 return self::ASN1_INTEGER_TAG . chr(strlen($part)) . $part;
125 }
126
127 private static function rawSignatureToDer(string $rawSignature) : string{
128 if(strlen($rawSignature) !== self::SIGNATURE_PART_LENGTH * 2){
129 throw new JwtException("JWT signature has unexpected length, expected 96, got " . strlen($rawSignature));
130 }
131
132 [$rString, $sString] = str_split($rawSignature, self::SIGNATURE_PART_LENGTH);
133 $sequence = self::signaturePartToAsn1($rString) . self::signaturePartToAsn1($sString);
134
135 //we can assume the length is 1 byte here - if it were larger than 127, more complex logic would be needed
136 assert(strlen($sequence) <= 127);
137 return self::ASN1_SEQUENCE_TAG . chr(strlen($sequence)) . $sequence;
138 }
139
140 private static function signaturePartFromAsn1(ByteBufferReader $stream) : string{
141 $prefix = $stream->readByteArray(1);
142 if($prefix !== self::ASN1_INTEGER_TAG){
143 throw new \InvalidArgumentException("Expected an ASN.1 INTEGER tag, got " . bin2hex($prefix));
144 }
145 //we can assume the length is 1 byte here - if it were larger than 127, more complex logic would be needed
146 $length = Byte::readUnsigned($stream);
147 if($length > self::SIGNATURE_PART_LENGTH + 1){ //each part may have an extra leading 0 byte to prevent it being interpreted as a negative number
148 throw new \InvalidArgumentException("Expected at most 49 bytes for signature R or S, got $length");
149 }
150 $part = $stream->readByteArray($length);
151 return str_pad(ltrim($part, "\x00"), self::SIGNATURE_PART_LENGTH, "\x00", STR_PAD_LEFT);
152 }
153
154 private static function rawSignatureFromDer(string $derSignature) : string{
155 if($derSignature[0] !== self::ASN1_SEQUENCE_TAG){
156 throw new \InvalidArgumentException("Invalid DER signature, expected ASN.1 SEQUENCE tag, got " . bin2hex($derSignature[0]));
157 }
158
159 //we can assume the length is 1 byte here - if it were larger than 127, more complex logic would be needed
160 $length = ord($derSignature[1]);
161 $parts = substr($derSignature, 2, $length);
162 if(strlen($parts) !== $length){
163 throw new \InvalidArgumentException("Invalid DER signature, expected $length sequence bytes, got " . strlen($parts));
164 }
165
166 $stream = new ByteBufferReader($parts);
167 $rRaw = self::signaturePartFromAsn1($stream);
168 $sRaw = self::signaturePartFromAsn1($stream);
169
170 if($stream->getUnreadLength() > 0){
171 throw new \InvalidArgumentException("Invalid DER signature, unexpected trailing sequence data");
172 }
173
174 return $rRaw . $sRaw;
175 }
176
180 public static function verify(string $jwt, string $signingKeyDer, bool $ec) : bool{
181 [$header, $body, $signature] = self::split($jwt);
182
183 $rawSignature = self::b64UrlDecode($signature);
184 $derSignature = $ec ? self::rawSignatureToDer($rawSignature) : $rawSignature;
185
186 $v = openssl_verify(
187 $header . '.' . $body,
188 $derSignature,
189 self::parseDerPublicKey($signingKeyDer),
190 $ec ? self::SIGNATURE_ALGORITHM : OPENSSL_ALGO_SHA256
191 );
192 switch($v){
193 case 0: return false;
194 case 1: return true;
195 case -1: throw new JwtException("Error verifying JWT signature: " . openssl_error_string());
196 default: throw new AssumptionFailedError("openssl_verify() should only return -1, 0 or 1");
197 }
198 }
199
204 public static function create(array $header, array $claims, \OpenSSLAsymmetricKey $signingKey) : string{
205 $jwtBody = JwtUtils::b64UrlEncode(json_encode($header, JSON_THROW_ON_ERROR)) . "." . JwtUtils::b64UrlEncode(json_encode($claims, JSON_THROW_ON_ERROR));
206
207 openssl_sign(
208 $jwtBody,
209 $derSignature,
210 $signingKey,
211 self::SIGNATURE_ALGORITHM
212 );
213
214 $rawSignature = self::rawSignatureFromDer($derSignature);
215 $jwtSig = self::b64UrlEncode($rawSignature);
216
217 return "$jwtBody.$jwtSig";
218 }
219
220 public static function b64UrlEncode(string $str) : string{
221 return rtrim(strtr(base64_encode($str), '+/', '-_'), '=');
222 }
223
224 public static function b64UrlDecode(string $str) : string{
225 if(($len = strlen($str) % 4) !== 0){
226 $str .= str_repeat('=', 4 - $len);
227 }
228 $decoded = base64_decode(strtr($str, '-_', '+/'), true);
229 if($decoded === false){
230 throw new JwtException("Malformed base64url encoded payload could not be decoded");
231 }
232 return $decoded;
233 }
234
235 public static function emitDerPublicKey(\OpenSSLAsymmetricKey $opensslKey) : string{
236 $details = Utils::assumeNotFalse(openssl_pkey_get_details($opensslKey), "Failed to get details from OpenSSL key resource");
238 $pemKey = $details['key'];
239 if(preg_match("@^-----BEGIN[A-Z\d ]+PUBLIC KEY-----\n([A-Za-z\d+/\n]+)\n-----END[A-Z\d ]+PUBLIC KEY-----\n$@", $pemKey, $matches) === 1){
240 $derKey = base64_decode(str_replace("\n", "", $matches[1]), true);
241 if($derKey !== false){
242 return $derKey;
243 }
244 }
245 throw new AssumptionFailedError("OpenSSL resource contains invalid public key");
246 }
247
254 private static function encodeDerLength(int $length) : string{
255 if ($length <= 0x7F) {
256 return chr($length);
257 }
258
259 $lengthBytes = ltrim(BE::packUnsignedInt($length), "\x00");
260
261 assert(strlen($lengthBytes) <= 4);
262 return chr(0x80 | strlen($lengthBytes)) . $lengthBytes;
263 }
264
268 private static function encodeDerBytes(int $tag, string $data) : string{
269 return chr($tag) . self::encodeDerLength(strlen($data)) . $data;
270 }
271
272 public static function parseDerPublicKey(string $derKey) : \OpenSSLAsymmetricKey{
273 $signingKeyOpenSSL = openssl_pkey_get_public(self::derPublicKeyToPem($derKey));
274 if($signingKeyOpenSSL === false){
275 throw new JwtException("OpenSSL failed to parse key: " . openssl_error_string());
276 }
277 return $signingKeyOpenSSL;
278 }
279
280 public static function derPublicKeyToPem(string $derKey) : string{
281 return sprintf("-----BEGIN PUBLIC KEY-----\n%s\n-----END PUBLIC KEY-----\n", base64_encode($derKey));
282 }
283
290 public static function rsaPublicKeyModExpToDer(string $nBase64, string $eBase64) : string{
291 $mod = self::b64UrlDecode($nBase64);
292 $exp = self::b64UrlDecode($eBase64);
293
294 $modulus = self::encodeDerBytes(2, $mod);
295 $publicExponent = self::encodeDerBytes(2, $exp);
296
297 $rsaPublicKey = self::encodeDerBytes(48, $modulus . $publicExponent);
298
299 // sequence(oid(1.2.840.113549.1.1.1), null)) = rsaEncryption.
300 $rsaOID = hex2bin('300d06092a864886f70d0101010500'); // hex version of MA0GCSqGSIb3DQEBAQUA
301 $rsaPublicKey = chr(0) . $rsaPublicKey;
302 $rsaPublicKey = self::encodeDerBytes(3, $rsaPublicKey);
303
304 return self::encodeDerBytes(48, $rsaOID . $rsaPublicKey);
305 }
306}
static split(string $jwt)
Definition JwtUtils.php:79
static verify(string $jwt, string $signingKeyDer, bool $ec)
Definition JwtUtils.php:180
static rsaPublicKeyModExpToDer(string $nBase64, string $eBase64)
Definition JwtUtils.php:290
static create(array $header, array $claims, \OpenSSLAsymmetricKey $signingKey)
Definition JwtUtils.php:204
static parse(string $token)
Definition JwtUtils.php:97