PocketMine-MP 5.35.1 git-e32e836dad793a3a3c8ddd8927c00e112b1e576a
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 base64_decode;
32use function base64_encode;
33use function bin2hex;
34use function chr;
35use function count;
36use function explode;
37use function hex2bin;
38use function is_array;
39use function json_decode;
40use function json_encode;
41use function json_last_error_msg;
42use function ltrim;
43use function openssl_error_string;
44use function openssl_pkey_get_details;
45use function openssl_pkey_get_public;
46use function openssl_sign;
47use function openssl_verify;
48use function ord;
49use function preg_match;
50use function rtrim;
51use function sprintf;
52use function str_pad;
53use function str_repeat;
54use function str_replace;
55use function str_split;
56use function strlen;
57use function strtr;
58use function substr;
59use const JSON_THROW_ON_ERROR;
60use const OPENSSL_ALGO_SHA256;
61use const OPENSSL_ALGO_SHA384;
62use const STR_PAD_LEFT;
63
64final class JwtUtils{
65 public const BEDROCK_SIGNING_KEY_CURVE_NAME = "secp384r1";
66
67 private const ASN1_INTEGER_TAG = "\x02";
68 private const ASN1_SEQUENCE_TAG = "\x30";
69
70 private const SIGNATURE_PART_LENGTH = 48;
71 private const SIGNATURE_ALGORITHM = OPENSSL_ALGO_SHA384;
72
78 public static function split(string $jwt) : array{
79 //limit of 4 allows us to detect too many parts without having to split the string up into a potentially large
80 //number of parts
81 $v = explode(".", $jwt, limit: 4);
82 if(count($v) !== 3){
83 throw new JwtException("Expected exactly 3 JWT parts delimited by a period");
84 }
85 return [$v[0], $v[1], $v[2]]; //workaround phpstan bug
86 }
87
96 public static function parse(string $token) : array{
97 $v = self::split($token);
98 $header = json_decode(self::b64UrlDecode($v[0]), true);
99 if(!is_array($header)){
100 throw new JwtException("Failed to decode JWT header JSON: " . json_last_error_msg());
101 }
102 $body = json_decode(self::b64UrlDecode($v[1]), true);
103 if(!is_array($body)){
104 throw new JwtException("Failed to decode JWT payload JSON: " . json_last_error_msg());
105 }
106 $signature = self::b64UrlDecode($v[2]);
107 return [$header, $body, $signature];
108 }
109
110 private static function signaturePartToAsn1(string $part) : string{
111 if(strlen($part) !== self::SIGNATURE_PART_LENGTH){
112 throw new JwtException("R and S for a SHA384 signature must each be exactly 48 bytes, but have " . strlen($part) . " bytes");
113 }
114 $part = ltrim($part, "\x00");
115 if(ord($part[0]) >= 128){
116 //ASN.1 integers with a leading 1 bit are considered negative - add a leading 0 byte to prevent this
117 //ECDSA signature R and S values are always positive
118 $part = "\x00" . $part;
119 }
120
121 //we can assume the length is 1 byte here - if it were larger than 127, more complex logic would be needed
122 return self::ASN1_INTEGER_TAG . chr(strlen($part)) . $part;
123 }
124
125 private static function rawSignatureToDer(string $rawSignature) : string{
126 if(strlen($rawSignature) !== self::SIGNATURE_PART_LENGTH * 2){
127 throw new JwtException("JWT signature has unexpected length, expected 96, got " . strlen($rawSignature));
128 }
129
130 [$rString, $sString] = str_split($rawSignature, self::SIGNATURE_PART_LENGTH);
131 $sequence = self::signaturePartToAsn1($rString) . self::signaturePartToAsn1($sString);
132
133 //we can assume the length is 1 byte here - if it were larger than 127, more complex logic would be needed
134 return self::ASN1_SEQUENCE_TAG . chr(strlen($sequence)) . $sequence;
135 }
136
137 private static function signaturePartFromAsn1(ByteBufferReader $stream) : string{
138 $prefix = $stream->readByteArray(1);
139 if($prefix !== self::ASN1_INTEGER_TAG){
140 throw new \InvalidArgumentException("Expected an ASN.1 INTEGER tag, got " . bin2hex($prefix));
141 }
142 //we can assume the length is 1 byte here - if it were larger than 127, more complex logic would be needed
143 $length = Byte::readUnsigned($stream);
144 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
145 throw new \InvalidArgumentException("Expected at most 49 bytes for signature R or S, got $length");
146 }
147 $part = $stream->readByteArray($length);
148 return str_pad(ltrim($part, "\x00"), self::SIGNATURE_PART_LENGTH, "\x00", STR_PAD_LEFT);
149 }
150
151 private static function rawSignatureFromDer(string $derSignature) : string{
152 if($derSignature[0] !== self::ASN1_SEQUENCE_TAG){
153 throw new \InvalidArgumentException("Invalid DER signature, expected ASN.1 SEQUENCE tag, got " . bin2hex($derSignature[0]));
154 }
155
156 //we can assume the length is 1 byte here - if it were larger than 127, more complex logic would be needed
157 $length = ord($derSignature[1]);
158 $parts = substr($derSignature, 2, $length);
159 if(strlen($parts) !== $length){
160 throw new \InvalidArgumentException("Invalid DER signature, expected $length sequence bytes, got " . strlen($parts));
161 }
162
163 $stream = new ByteBufferReader($parts);
164 $rRaw = self::signaturePartFromAsn1($stream);
165 $sRaw = self::signaturePartFromAsn1($stream);
166
167 if($stream->getUnreadLength() > 0){
168 throw new \InvalidArgumentException("Invalid DER signature, unexpected trailing sequence data");
169 }
170
171 return $rRaw . $sRaw;
172 }
173
177 public static function verify(string $jwt, string $signingKeyDer, bool $ec) : bool{
178 [$header, $body, $signature] = self::split($jwt);
179
180 $rawSignature = self::b64UrlDecode($signature);
181 $derSignature = $ec ? self::rawSignatureToDer($rawSignature) : $rawSignature;
182
183 $v = openssl_verify(
184 $header . '.' . $body,
185 $derSignature,
186 self::derPublicKeyToPem($signingKeyDer),
187 $ec ? self::SIGNATURE_ALGORITHM : OPENSSL_ALGO_SHA256
188 );
189 switch($v){
190 case 0: return false;
191 case 1: return true;
192 case -1: throw new JwtException("Error verifying JWT signature: " . openssl_error_string());
193 default: throw new AssumptionFailedError("openssl_verify() should only return -1, 0 or 1");
194 }
195 }
196
201 public static function create(array $header, array $claims, \OpenSSLAsymmetricKey $signingKey) : string{
202 $jwtBody = JwtUtils::b64UrlEncode(json_encode($header, JSON_THROW_ON_ERROR)) . "." . JwtUtils::b64UrlEncode(json_encode($claims, JSON_THROW_ON_ERROR));
203
204 openssl_sign(
205 $jwtBody,
206 $derSignature,
207 $signingKey,
208 self::SIGNATURE_ALGORITHM
209 );
210
211 $rawSignature = self::rawSignatureFromDer($derSignature);
212 $jwtSig = self::b64UrlEncode($rawSignature);
213
214 return "$jwtBody.$jwtSig";
215 }
216
217 public static function b64UrlEncode(string $str) : string{
218 return rtrim(strtr(base64_encode($str), '+/', '-_'), '=');
219 }
220
221 public static function b64UrlDecode(string $str) : string{
222 if(($len = strlen($str) % 4) !== 0){
223 $str .= str_repeat('=', 4 - $len);
224 }
225 $decoded = base64_decode(strtr($str, '-_', '+/'), true);
226 if($decoded === false){
227 throw new JwtException("Malformed base64url encoded payload could not be decoded");
228 }
229 return $decoded;
230 }
231
232 public static function emitDerPublicKey(\OpenSSLAsymmetricKey $opensslKey) : string{
233 $details = Utils::assumeNotFalse(openssl_pkey_get_details($opensslKey), "Failed to get details from OpenSSL key resource");
235 $pemKey = $details['key'];
236 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){
237 $derKey = base64_decode(str_replace("\n", "", $matches[1]), true);
238 if($derKey !== false){
239 return $derKey;
240 }
241 }
242 throw new AssumptionFailedError("OpenSSL resource contains invalid public key");
243 }
244
249 private static function encodeDerLength(int $length) : string{
250 if ($length <= 0x7F) {
251 return chr($length);
252 }
253
254 $lengthBytes = ltrim(BE::packUnsignedInt($length), "\x00");
255
256 return chr(0x80 | strlen($lengthBytes)) . $lengthBytes;
257 }
258
259 private static function encodeDerBytes(int $tag, string $data) : string{
260 return chr($tag) . self::encodeDerLength(strlen($data)) . $data;
261 }
262
263 public static function parseDerPublicKey(string $derKey) : \OpenSSLAsymmetricKey{
264 $signingKeyOpenSSL = openssl_pkey_get_public(self::derPublicKeyToPem($derKey));
265 if($signingKeyOpenSSL === false){
266 throw new JwtException("OpenSSL failed to parse key: " . openssl_error_string());
267 }
268 return $signingKeyOpenSSL;
269 }
270
271 public static function derPublicKeyToPem(string $derKey) : string{
272 return sprintf("-----BEGIN PUBLIC KEY-----\n%s\n-----END PUBLIC KEY-----\n", base64_encode($derKey));
273 }
274
281 public static function rsaPublicKeyModExpToDer(string $nBase64, string $eBase64) : string{
282 $mod = self::b64UrlDecode($nBase64);
283 $exp = self::b64UrlDecode($eBase64);
284
285 $modulus = self::encodeDerBytes(2, $mod);
286 $publicExponent = self::encodeDerBytes(2, $exp);
287
288 $rsaPublicKey = self::encodeDerBytes(48, $modulus . $publicExponent);
289
290 // sequence(oid(1.2.840.113549.1.1.1), null)) = rsaEncryption.
291 $rsaOID = hex2bin('300d06092a864886f70d0101010500'); // hex version of MA0GCSqGSIb3DQEBAQUA
292 $rsaPublicKey = chr(0) . $rsaPublicKey;
293 $rsaPublicKey = self::encodeDerBytes(3, $rsaPublicKey);
294
295 return self::encodeDerBytes(48, $rsaOID . $rsaPublicKey);
296 }
297}
static split(string $jwt)
Definition JwtUtils.php:78
static verify(string $jwt, string $signingKeyDer, bool $ec)
Definition JwtUtils.php:177
static rsaPublicKeyModExpToDer(string $nBase64, string $eBase64)
Definition JwtUtils.php:281
static create(array $header, array $claims, \OpenSSLAsymmetricKey $signingKey)
Definition JwtUtils.php:201
static parse(string $token)
Definition JwtUtils.php:96