PocketMine-MP 5.27.1 git-9af3cde03fabbe4129c79e46dc87ffa0fff446e6
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
29use function base64_decode;
30use function base64_encode;
31use function bin2hex;
32use function chr;
33use function count;
34use function explode;
35use function is_array;
36use function json_decode;
37use function json_encode;
38use function json_last_error_msg;
39use function ltrim;
40use function openssl_error_string;
41use function openssl_pkey_get_details;
42use function openssl_pkey_get_public;
43use function openssl_sign;
44use function openssl_verify;
45use function ord;
46use function preg_match;
47use function rtrim;
48use function sprintf;
49use function str_pad;
50use function str_repeat;
51use function str_replace;
52use function str_split;
53use function strlen;
54use function strtr;
55use function substr;
56use const JSON_THROW_ON_ERROR;
57use const OPENSSL_ALGO_SHA384;
58use const STR_PAD_LEFT;
59
60final class JwtUtils{
61 public const BEDROCK_SIGNING_KEY_CURVE_NAME = "secp384r1";
62
63 private const ASN1_INTEGER_TAG = "\x02";
64 private const ASN1_SEQUENCE_TAG = "\x30";
65
66 private const SIGNATURE_PART_LENGTH = 48;
67 private const SIGNATURE_ALGORITHM = OPENSSL_ALGO_SHA384;
68
74 public static function split(string $jwt) : array{
75 //limit of 4 allows us to detect too many parts without having to split the string up into a potentially large
76 //number of parts
77 $v = explode(".", $jwt, limit: 4);
78 if(count($v) !== 3){
79 throw new JwtException("Expected exactly 3 JWT parts delimited by a period");
80 }
81 return [$v[0], $v[1], $v[2]]; //workaround phpstan bug
82 }
83
92 public static function parse(string $token) : array{
93 $v = self::split($token);
94 $header = json_decode(self::b64UrlDecode($v[0]), true);
95 if(!is_array($header)){
96 throw new JwtException("Failed to decode JWT header JSON: " . json_last_error_msg());
97 }
98 $body = json_decode(self::b64UrlDecode($v[1]), true);
99 if(!is_array($body)){
100 throw new JwtException("Failed to decode JWT payload JSON: " . json_last_error_msg());
101 }
102 $signature = self::b64UrlDecode($v[2]);
103 return [$header, $body, $signature];
104 }
105
106 private static function signaturePartToAsn1(string $part) : string{
107 if(strlen($part) !== self::SIGNATURE_PART_LENGTH){
108 throw new JwtException("R and S for a SHA384 signature must each be exactly 48 bytes, but have " . strlen($part) . " bytes");
109 }
110 $part = ltrim($part, "\x00");
111 if(ord($part[0]) >= 128){
112 //ASN.1 integers with a leading 1 bit are considered negative - add a leading 0 byte to prevent this
113 //ECDSA signature R and S values are always positive
114 $part = "\x00" . $part;
115 }
116
117 //we can assume the length is 1 byte here - if it were larger than 127, more complex logic would be needed
118 return self::ASN1_INTEGER_TAG . chr(strlen($part)) . $part;
119 }
120
121 private static function rawSignatureToDer(string $rawSignature) : string{
122 if(strlen($rawSignature) !== self::SIGNATURE_PART_LENGTH * 2){
123 throw new JwtException("JWT signature has unexpected length, expected 96, got " . strlen($rawSignature));
124 }
125
126 [$rString, $sString] = str_split($rawSignature, self::SIGNATURE_PART_LENGTH);
127 $sequence = self::signaturePartToAsn1($rString) . self::signaturePartToAsn1($sString);
128
129 //we can assume the length is 1 byte here - if it were larger than 127, more complex logic would be needed
130 return self::ASN1_SEQUENCE_TAG . chr(strlen($sequence)) . $sequence;
131 }
132
133 private static function signaturePartFromAsn1(BinaryStream $stream) : string{
134 $prefix = $stream->get(1);
135 if($prefix !== self::ASN1_INTEGER_TAG){
136 throw new \InvalidArgumentException("Expected an ASN.1 INTEGER tag, got " . bin2hex($prefix));
137 }
138 //we can assume the length is 1 byte here - if it were larger than 127, more complex logic would be needed
139 $length = $stream->getByte();
140 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
141 throw new \InvalidArgumentException("Expected at most 49 bytes for signature R or S, got $length");
142 }
143 $part = $stream->get($length);
144 return str_pad(ltrim($part, "\x00"), self::SIGNATURE_PART_LENGTH, "\x00", STR_PAD_LEFT);
145 }
146
147 private static function rawSignatureFromDer(string $derSignature) : string{
148 if($derSignature[0] !== self::ASN1_SEQUENCE_TAG){
149 throw new \InvalidArgumentException("Invalid DER signature, expected ASN.1 SEQUENCE tag, got " . bin2hex($derSignature[0]));
150 }
151
152 //we can assume the length is 1 byte here - if it were larger than 127, more complex logic would be needed
153 $length = ord($derSignature[1]);
154 $parts = substr($derSignature, 2, $length);
155 if(strlen($parts) !== $length){
156 throw new \InvalidArgumentException("Invalid DER signature, expected $length sequence bytes, got " . strlen($parts));
157 }
158
159 $stream = new BinaryStream($parts);
160 $rRaw = self::signaturePartFromAsn1($stream);
161 $sRaw = self::signaturePartFromAsn1($stream);
162
163 if(!$stream->feof()){
164 throw new \InvalidArgumentException("Invalid DER signature, unexpected trailing sequence data");
165 }
166
167 return $rRaw . $sRaw;
168 }
169
173 public static function verify(string $jwt, \OpenSSLAsymmetricKey $signingKey) : bool{
174 [$header, $body, $signature] = self::split($jwt);
175
176 $rawSignature = self::b64UrlDecode($signature);
177 $derSignature = self::rawSignatureToDer($rawSignature);
178
179 $v = openssl_verify(
180 $header . '.' . $body,
181 $derSignature,
182 $signingKey,
183 self::SIGNATURE_ALGORITHM
184 );
185 switch($v){
186 case 0: return false;
187 case 1: return true;
188 case -1: throw new JwtException("Error verifying JWT signature: " . openssl_error_string());
189 default: throw new AssumptionFailedError("openssl_verify() should only return -1, 0 or 1");
190 }
191 }
192
197 public static function create(array $header, array $claims, \OpenSSLAsymmetricKey $signingKey) : string{
198 $jwtBody = JwtUtils::b64UrlEncode(json_encode($header, JSON_THROW_ON_ERROR)) . "." . JwtUtils::b64UrlEncode(json_encode($claims, JSON_THROW_ON_ERROR));
199
200 openssl_sign(
201 $jwtBody,
202 $derSignature,
203 $signingKey,
204 self::SIGNATURE_ALGORITHM
205 );
206
207 $rawSignature = self::rawSignatureFromDer($derSignature);
208 $jwtSig = self::b64UrlEncode($rawSignature);
209
210 return "$jwtBody.$jwtSig";
211 }
212
213 public static function b64UrlEncode(string $str) : string{
214 return rtrim(strtr(base64_encode($str), '+/', '-_'), '=');
215 }
216
217 public static function b64UrlDecode(string $str) : string{
218 if(($len = strlen($str) % 4) !== 0){
219 $str .= str_repeat('=', 4 - $len);
220 }
221 $decoded = base64_decode(strtr($str, '-_', '+/'), true);
222 if($decoded === false){
223 throw new JwtException("Malformed base64url encoded payload could not be decoded");
224 }
225 return $decoded;
226 }
227
228 public static function emitDerPublicKey(\OpenSSLAsymmetricKey $opensslKey) : string{
229 $details = Utils::assumeNotFalse(openssl_pkey_get_details($opensslKey), "Failed to get details from OpenSSL key resource");
231 $pemKey = $details['key'];
232 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){
233 $derKey = base64_decode(str_replace("\n", "", $matches[1]), true);
234 if($derKey !== false){
235 return $derKey;
236 }
237 }
238 throw new AssumptionFailedError("OpenSSL resource contains invalid public key");
239 }
240
241 public static function parseDerPublicKey(string $derKey) : \OpenSSLAsymmetricKey{
242 $signingKeyOpenSSL = openssl_pkey_get_public(sprintf("-----BEGIN PUBLIC KEY-----\n%s\n-----END PUBLIC KEY-----\n", base64_encode($derKey)));
243 if($signingKeyOpenSSL === false){
244 throw new JwtException("OpenSSL failed to parse key: " . openssl_error_string());
245 }
246 $details = openssl_pkey_get_details($signingKeyOpenSSL);
247 if($details === false){
248 throw new JwtException("OpenSSL failed to get details from key: " . openssl_error_string());
249 }
250 if(!isset($details['ec']['curve_name'])){
251 throw new JwtException("Expected an EC key");
252 }
253 $curve = $details['ec']['curve_name'];
254 if($curve !== self::BEDROCK_SIGNING_KEY_CURVE_NAME){
255 throw new JwtException("Key must belong to curve " . self::BEDROCK_SIGNING_KEY_CURVE_NAME . ", got $curve");
256 }
257 return $signingKeyOpenSSL;
258 }
259}
static split(string $jwt)
Definition JwtUtils.php:74
static verify(string $jwt, \OpenSSLAsymmetricKey $signingKey)
Definition JwtUtils.php:173
static create(array $header, array $claims, \OpenSSLAsymmetricKey $signingKey)
Definition JwtUtils.php:197
static parse(string $token)
Definition JwtUtils.php:92