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