diff --git a/src/network/mcpe/NetworkSession.php b/src/network/mcpe/NetworkSession.php index 0a61e0ed4..8e3d0dfc0 100644 --- a/src/network/mcpe/NetworkSession.php +++ b/src/network/mcpe/NetworkSession.php @@ -670,7 +670,7 @@ class NetworkSession{ } $this->sendDataPacket(ServerToClientHandshakePacket::create($handshakeJwt), true); //make sure this gets sent before encryption is enabled - $this->cipher = new EncryptionContext($encryptionKey, EncryptionContext::ENCRYPTION_SCHEME); + $this->cipher = EncryptionContext::fakeGCM($encryptionKey); $this->setHandler(new HandshakePacketHandler(function() : void{ $this->onServerLoginSuccess(); diff --git a/src/network/mcpe/encryption/EncryptionContext.php b/src/network/mcpe/encryption/EncryptionContext.php index 270d40d43..18d469468 100644 --- a/src/network/mcpe/encryption/EncryptionContext.php +++ b/src/network/mcpe/encryption/EncryptionContext.php @@ -32,7 +32,6 @@ use function strlen; use function substr; class EncryptionContext{ - public const ENCRYPTION_SCHEME = "AES-256-GCM"; private const CHECKSUM_ALGO = "sha256"; /** @var bool */ @@ -51,16 +50,40 @@ class EncryptionContext{ /** @var int */ private $encryptCounter = 0; - public function __construct(string $encryptionKey, string $algorithm){ + public function __construct(string $encryptionKey, string $algorithm, string $iv){ $this->key = $encryptionKey; $this->decryptCipher = new Cipher($algorithm); - $ivLength = $this->decryptCipher->getIVLength(); - $this->decryptCipher->decryptInit($this->key, substr($this->key, 0, $ivLength)); + $this->decryptCipher->decryptInit($this->key, $iv); $this->encryptCipher = new Cipher($algorithm); - $ivLength = $this->encryptCipher->getIVLength(); - $this->encryptCipher->encryptInit($this->key, substr($this->key, 0, $ivLength)); + $this->encryptCipher->encryptInit($this->key, $iv); + } + + /** + * Returns an EncryptionContext suitable for decrypting Minecraft packets from 1.16.200 and up. + * + * MCPE uses GCM, but without the auth tag, which defeats the whole purpose of using GCM. + * GCM is just a wrapper around CTR which adds the auth tag, so CTR can replace GCM for this case. + * However, since GCM passes only the first 12 bytes of the IV followed by 0002, we must do the same for + * compatibility with MCPE. + * In PM, we could skip this and just use GCM directly (since we use OpenSSL), but this way is more portable, and + * better for developers who come digging in the PM code looking for answers. + */ + public static function fakeGCM(string $encryptionKey) : self{ + return new EncryptionContext( + $encryptionKey, + "AES-256-CTR", + substr($encryptionKey, 0, 12) . "\x00\x00\x00\x02" + ); + } + + public static function cfb8(string $encryptionKey) : self{ + return new EncryptionContext( + $encryptionKey, + "AES-256-CFB8", + substr($encryptionKey, 0, 16) + ); } /**