Ejemplo n.º 1
0
        private string _ToASNPrivateKey()
        {
            RSAParameters privateKey = this._rsa.ExportParameters(true);

            AsnKeyBuilder.AsnMessage key = AsnKeyBuilder.PrivateKeyToPKCS8(privateKey);

            return(Convert.ToBase64String(key.GetBytes()));
        }
Ejemplo n.º 2
0
        private string _ToDERPrivateKey()
        {
            RSAParameters privateKey = this._rsa.ExportParameters(true);

            AsnKeyBuilder.AsnMessage key = AsnKeyBuilder.PrivateKeyToPKCS1(privateKey);

            return(deal_string.encode_hex(key.GetBytes()));
        }
Ejemplo n.º 3
0
        private string _ToASNPublicKey()
        {
            RSAParameters publicKey = this._rsa.ExportParameters(false);

            AsnKeyBuilder.AsnMessage key = AsnKeyBuilder.PublicKeyToX509(publicKey);

            return(Convert.ToBase64String(key.GetBytes()));
        }
Ejemplo n.º 4
0
        public string ToASNKey()
        {
            if (_asn == null)
            {
                AsnKeyBuilder.AsnMessage asn = AsnKeyBuilder.PrivateKeyToPKCS8(this._key);
                _asn = Convert.ToBase64String(asn.GetBytes());
            }

            return(_asn);
        }
Ejemplo n.º 5
0
        public void Receive(ref MinecraftClient client, GameStream stream)
        {
            VarInt secretLength = stream.ReadVarInt();

            byte[] sharedSecret = stream.ReadByteArray((int)secretLength.Value);
            VarInt tokenLength  = stream.ReadVarInt();

            byte[] verifyToken = stream.ReadByteArray((int)tokenLength.Value);

            var decryptedToken = Protocol.CryptoProvider.Decrypt(verifyToken, false);

            for (int i = 0; i < decryptedToken.Length; i++)
            {
                if (decryptedToken[i] != client.VerifyToken[i])
                {
                    client.Disconnect("Unable to authenticate");
                    return;
                }
            }

            client.SharedToken = Protocol.CryptoProvider.Decrypt(sharedSecret, false);
            AsnKeyBuilder.AsnMessage encodedKey = AsnKeyBuilder.PublicKeyToX509(Protocol.Key);
            byte[] shaData = Encoding.UTF8.GetBytes(Protocol.ServerID)
                             .Concat(client.SharedToken)
                             .Concat(encodedKey.GetBytes()).ToArray();
            string hash = Cryptography.JavaHexDigest(shaData);

            WebClient    webClient = new();
            StreamReader webReader = new(webClient.OpenRead(
                                             new Uri(string.Format(SessionChecker, client.Player.Username, hash))
                                             ));

            string response = webReader.ReadToEnd();

            webReader.Close();
            JToken json = JToken.Parse(response);

            if (string.IsNullOrEmpty(response))
            {
                client.Disconnect("Failed to verify username");
                return;
            }

            client.Stream = new(new AesStream(client.Stream.BaseStream, client.SharedToken));
            string?uuid = json["id"] !.Value <string>();

            if (uuid != client.Player.UniqueId.toString().Remove('-'))
            {
                client.Disconnect("Failed to verify UniqueID");
                return;
            }

            client.EncryptionPassed = true;
            new LoginSuccess(true).Send(ref client, client.Stream);
        }
        public static String ExportPublicKeyToX509PEM(RSACryptoServiceProvider csp)   // x509
        {
            // Encoded key
            AsnKeyBuilder.AsnMessage key = null;
            // actualKey
            RSAParameters actualKey = csp.ExportParameters(false);

            key = AsnKeyBuilder.PublicKeyToX509(actualKey);

            return(packagePEM(key.GetBytes(), PEMtypes.PEM_PUBLIC));
        }
        public static String ExportPrivateKeyToPKCS8PEM(RSACryptoServiceProvider csp)   // PKCS8
        {
            // Encoded key
            AsnKeyBuilder.AsnMessage key = null;
            // actualKey
            RSAParameters actualKey = csp.ExportParameters(true);

            key = AsnKeyBuilder.PrivateKeyToPKCS8(actualKey);

            return(packagePEM(key.GetBytes(), PEMtypes.PEM_RSA));
        }
Ejemplo n.º 8
0
        private static void CreateDsaKeys()
        {
            CspParameters csp = new CspParameters
            {
                KeyContainerName = "DSA Test (OK to Delete)"
            };

            const int PROV_DSS_DH = 13;

            csp.ProviderType = PROV_DSS_DH;

            // Can't use AT_EXCHANGE for creation. This is
            //  a signature algorithm
            const int AT_SIGNATURE = 2;

            csp.KeyNumber = AT_SIGNATURE;

            DSACryptoServiceProvider dsa = new DSACryptoServiceProvider(1024, csp)
            {
                PersistKeyInCsp = false
            };

            // Encoded key
            AsnKeyBuilder.AsnMessage key = null;

            // Private Key
            DSAParameters privateKey = dsa.ExportParameters(true);

            key = AsnKeyBuilder.PrivateKeyToPKCS8(privateKey);

            using (BinaryWriter writer = new BinaryWriter(
                       new FileStream("private.dsa.cs.ber", FileMode.Create,
                                      FileAccess.ReadWrite)))
            {
                writer.Write(key.GetBytes());
            }

            // Public Key
            DSAParameters publicKey = dsa.ExportParameters(false);

            key = AsnKeyBuilder.PublicKeyToX509(publicKey);

            using (BinaryWriter writer = new BinaryWriter(
                       new FileStream("public.dsa.cs.ber", FileMode.Create,
                                      FileAccess.ReadWrite)))
            {
                writer.Write(key.GetBytes());
            }

            // See http://blogs.msdn.com/tess/archive/2007/10/31/
            //   asp-net-crash-system-security-cryptography-cryptographicexception.aspx
            dsa.Clear();
        }
Ejemplo n.º 9
0
        public static void EncryptionKeyResponse(RemoteClient client, MinecraftServer server, IPacket _packet)
        {
            var packet         = (EncryptionKeyResponsePacket)_packet;
            var decryptedToken = server.CryptoServiceProvider.Decrypt(packet.VerificationToken, false);

            for (int i = 0; i < decryptedToken.Length; i++)
            {
                if (decryptedToken[i] != client.VerificationToken[i])
                {
                    client.Disconnect("Unable to authenticate.");
                    return;
                }
            }
            client.SharedKey = server.CryptoServiceProvider.Decrypt(packet.SharedSecret, false);
            // Create a hash for session verification
            AsnKeyBuilder.AsnMessage encodedKey = AsnKeyBuilder.PublicKeyToX509(server.ServerKey);
            byte[] shaData = Encoding.UTF8.GetBytes(client.ServerId)
                             .Concat(client.SharedKey)
                             .Concat(encodedKey.GetBytes()).ToArray();
            string hash = Cryptography.JavaHexDigest(shaData);

            // Talk to sessionserver.minecraft.net
            if (server.Settings.OnlineMode)
            {
                var webClient = new WebClient();
                var webReader = new StreamReader(webClient.OpenRead(
                                                     new Uri(string.Format(sessionCheckUri, client.Username, hash))));
                string response = webReader.ReadToEnd();
                webReader.Close();
                var json = JToken.Parse(response);
                if (string.IsNullOrEmpty(response))
                {
                    client.Disconnect("Failed to verify username!");
                    return;
                }
                client.UUID = json["id"].Value <string>();
            }
            client.NetworkStream             = new AesStream(client.NetworkClient.GetStream(), client.SharedKey);
            client.NetworkManager.BaseStream = client.NetworkStream;
            client.EncryptionEnabled         = true;
            var eventArgs = new ConnectionEstablishedEventArgs(client);

            server.OnConnectionEstablished(eventArgs);
            if (eventArgs.PermitConnection)
            {
                server.LogInPlayer(client);
            }
            else
            {
                client.Disconnect(eventArgs.DisconnectReason);
            }
        }
        public static String ExportPublicKeyToX509Hex(RSACryptoServiceProvider csp)   // x509
        {
            // Encoded key
            AsnKeyBuilder.AsnMessage key = null;
            // actualKey
            RSAParameters actualKey = csp.ExportParameters(false);

            key = AsnKeyBuilder.PublicKeyToX509(actualKey);

            var bytes = key.GetBytes();

            return(ByteToHex(bytes));
        }
        public static String ExportPublicKeyToX509Base64(RSACryptoServiceProvider csp)   // x509
        {
            // Encoded key
            AsnKeyBuilder.AsnMessage key = null;
            // actualKey
            RSAParameters actualKey = csp.ExportParameters(false);

            key = AsnKeyBuilder.PublicKeyToX509(actualKey);

            var bytes = key.GetBytes();

            return(Convert.ToBase64String(bytes, 0, (int)bytes.Length));
        }
Ejemplo n.º 12
0
        private string _ToASNPrivateKey()
        {
            if (_rsa.PublicOnly)
            {
                throw new Exception("not a private key");
            }

            RSAParameters privateKey = this._rsa.ExportParameters(true);

            AsnKeyBuilder.AsnMessage key = AsnKeyBuilder.PrivateKeyToPKCS8(privateKey);

            return(Convert.ToBase64String(key.GetBytes()));
        }
Ejemplo n.º 13
0
        public static void ClientStatus(MinecraftClient client, MinecraftServer server, IPacket _packet)
        {
            var packet = (ClientStatusPacket)_packet;

            if (packet.Status == ClientStatusPacket.ClientStatus.InitialSpawn)
            {
                // Create a hash for session verification
                SHA1 sha1 = SHA1.Create();
                AsnKeyBuilder.AsnMessage encodedKey = AsnKeyBuilder.PublicKeyToX509(server.ServerKey);
                byte[] shaData = Encoding.UTF8.GetBytes(client.AuthenticationHash)
                                 .Concat(client.SharedKey)
                                 .Concat(encodedKey.GetBytes()).ToArray();
                string hash = Cryptography.JavaHexDigest(shaData);

                // Talk to session.minecraft.net
                if (server.Settings.OnlineMode)
                {
                    var webClient = new WebClient();
                    var webReader = new StreamReader(webClient.OpenRead(
                                                         new Uri(string.Format(sessionCheckUri, client.Username, hash))));
                    string response = webReader.ReadToEnd();
                    webReader.Close();
                    if (response != "YES")
                    {
                        client.SendPacket(new DisconnectPacket("Failed to verify username!"));
                        return;
                    }
                }

                server.LogInPlayer(client);
            }
            else if (packet.Status == ClientStatusPacket.ClientStatus.Respawn)
            {
                var world = client.World;
                client.Entity.Position = new Vector3(
                    client.Entity.SpawnPoint.X,
                    // FIXME: This seems to drop the player camera from half the height of a login spawn
                    client.Entity.SpawnPoint.Y,
                    client.Entity.SpawnPoint.Z);
                client.Entity.Health         = client.Entity.MaxHealth;
                client.Entity.Food           = 20;
                client.Entity.FoodSaturation = 20;
                server.EntityManager.SpawnEntity(world, client.Entity);
                client.SendPacket(new UpdateHealthPacket(client.Entity.Health, client.Entity.Food, client.Entity.FoodSaturation));
                client.SendPacket(new RespawnPacket(Dimension.Overworld, server.Settings.Difficulty, client.Entity.GameMode, World.Height, world.LevelType));
                client.SendPacket(new PlayerPositionAndLookPacket(client.Entity.Position.X, client.Entity.Position.Y, client.Entity.Position.Z,
                                                                  client.Entity.Position.Y + PlayerEntity.Height, client.Entity.Yaw, client.Entity.Pitch, true));
            }
        }
Ejemplo n.º 14
0
        public static void ReceiveEncryptionResponse(Player player, GameStream stream)
        {
            VarInt secretLength = stream.ReadVarInt();

            byte[] sharedSecret = stream.ReadByteArray((int)secretLength.Value);
            VarInt tokenLength  = stream.ReadVarInt();

            byte[] verifyToken = stream.ReadByteArray((int)tokenLength.Value);

            var decryptedToken = Server.CryptoServerProvider.Decrypt(verifyToken, false);

            for (int i = 0; i < decryptedToken.Length; i++)
            {
                if (decryptedToken[i] != player.Stream.VerifyToken[i])
                {
                    Disconnect(player, stream, "Unable to authenticate");
                }
            }

            player.SharedToken = Server.CryptoServerProvider.Decrypt(sharedSecret, false);
            AsnKeyBuilder.AsnMessage encodedKey = AsnKeyBuilder.PublicKeyToX509(Server.ServerKey);
            byte[] shaData = Encoding.UTF8.GetBytes(Server.ID)
                             .Concat(player.SharedToken)
                             .Concat(encodedKey.GetBytes()).ToArray();
            string hash = Cryptography.JavaHexDigest(shaData);

            WebClient    webCLient = new WebClient();
            StreamReader webReader = new StreamReader(webCLient.OpenRead(
                                                          new Uri(string.Format(SessionChecker, player.Username, hash))
                                                          ));
            string response = webReader.ReadToEnd();

            webReader.Close();
            JToken json = JToken.Parse(response);

            if (string.IsNullOrEmpty(response))
            {
                Disconnect(player, stream, "Failed to verify username");
            }

            player.Stream            = new GameStream(new AesStream(player.Stream.BaseStream, player.SharedToken));
            player.UUID              = json["id"].Value <string>();
            player.EncryptionEnabled = true;
            SendSuccess(player, player.Stream);
        }
Ejemplo n.º 15
0
        private bool FinializeClientEncryption(EncryptionKeyResponsePacket encryptionKeyResponsePacket)
        {
            // Here, we need to prepare everything to enable client<->proxy
            // encryption, but we can't turn it on quite yet.

            if (Settings.AuthenticateClients)
            {
                // Do authentication
                // Create a hash for session verification
                AsnKeyBuilder.AsnMessage encodedKey = AsnKeyBuilder.PublicKeyToX509(ServerKey);
                byte[] shaData = Encoding.UTF8.GetBytes(ClientAuthenticationHash)
                                 .Concat(ClientSharedKey)
                                 .Concat(encodedKey.GetBytes()).ToArray();
                string hash = Cryptography.JavaHexDigest(shaData);

                var client = new WebClient();
                var result = client.DownloadString(string.Format("http://session.minecraft.net/game/checkserver.jsp?user={0}&serverId={1}",
                                                                 PlayerName, hash));
                if (result != "YES")
                {
                    Log.Write("Failed to authenticate " + PlayerName + "!");
                    ServerStream.WritePacket(new DisconnectPacket("Failed to authenticate!"), Craft.Net.PacketDirection.Serverbound);
                    ClientStream.WritePacket(new DisconnectPacket("Failed to authenticate!"), Craft.Net.PacketDirection.Clientbound);
                    Server.Flush();
                    Client.Flush();
                    return(false);
                }
            }

            // Send unencrypted response
            ServerStream.WritePacket(ServerEncryptionResponse, Craft.Net.PacketDirection.Serverbound);
            Server.Flush();

            // We wait for the server to respond, then set up encryption
            // for both sides of the connection.
            ServerStream.BaseStream = new AesStream(Server, ServerSharedKey);
            return(true);
        }