public void TestEncodeAndDecode() { HandshakePacket sentP = new HandshakePacket { DCIDLength = 2, DCID = new byte[] { 0x1a, 0x85 }, PacketNumberLength = 3, SCIDLength = 2, SCID = new byte[] { 0x09, 0x34 }, PacketNumber = 91235, Payload = new byte[] { 0x01, 0x10 }, }; byte[] b = sentP.Encode(); Packet p = Packet.Unpack(b); Assert.AreEqual(p.GetType(), typeof(HandshakePacket)); HandshakePacket recP = p as HandshakePacket; Assert.AreEqual((UInt32)2, recP.DCIDLength); CollectionAssert.AreEqual(new byte[] { 0x1a, 0x85 }, recP.DCID); Assert.AreEqual((UInt32)2, recP.SCIDLength); CollectionAssert.AreEqual(new byte[] { 0x09, 0x34 }, recP.SCID); Assert.AreEqual((UInt32)3, recP.PacketNumberLength); Assert.AreEqual((UInt32)91235, recP.PacketNumber); Assert.AreEqual((UInt64)5, recP.Length.Value); // 5 = PacketNumberLength + Payload.Length }
public Slave(HandshakePacket p, PacketHandler ph) { Name = p.Name; Address = IPAddress.Parse(p.Address); Port = p.Port; PacketHandler = ph; }
private void ContinueHandshake() { HandshakePacket hp = (HandshakePacket)ReadPacket(new HandshakePacket()); HandshakeMidPacket hmp = new HandshakeMidPacket(); SendPacket(hmp); _stream.ReadByte(); HandshakePacket hp2 = (HandshakePacket)ReadPacket(new HandshakePacket()); HandshakeMidPacket hmp2 = new HandshakeMidPacket(); SendPacket(hmp2); _stream.ReadByte(); HandshakePacket hp3 = (HandshakePacket)ReadPacket(new HandshakePacket()); HandshakeClosePacket hcp = new HandshakeClosePacket(); SendPacket(hcp); _needToDecrypt = true; _bufferSize = 8; }
public static void HandlePacketHandshake(Client client, HandshakePacket packet) { client.Username = packet.Username; if (!client.CheckUsername(packet.Username)) { client.Kick("Inconsistent username"); } if (packet.ProtocolVersion < ProtocolVersion) { client.Kick("Outdated client"); } else { client.Host = packet.ServerHost + ":" + packet.ServerPort; if (client.Server.EncryptionEnabled) { client.SendEncryptionRequest(); } else if (IsAuthenticated(client)) { Task.Factory.StartNew(client.SendLoginSequence); } } }
public override IEnumerable <AbstractPacket> GetSubPackets(bool includeSelfReference) { if (includeSelfReference) { yield return(this); } //I only care about the hadshake protocol if (this.contentType == ContentTypes.Handshake) { int subPacketStartIndex = PacketStartIndex + 5; while (subPacketStartIndex < PacketEndIndex) { AbstractPacket packet; if (this.contentType == ContentTypes.Handshake) { try { packet = new HandshakePacket(ParentFrame, subPacketStartIndex, PacketEndIndex); } catch { packet = new RawPacket(ParentFrame, subPacketStartIndex, PacketEndIndex); } } else { packet = new RawPacket(ParentFrame, subPacketStartIndex, PacketEndIndex); } subPacketStartIndex = packet.PacketEndIndex + 1; yield return(packet); } }//end handshake }
private void PerformHandshake() { var handshakePacket = new HandshakePacket(-1, "localhost", 25565, 1); var nPacket = new NotchianPacket(0x00, handshakePacket.Serialize()); socket.Send(nPacket.Serialize()); }
public void Connect(IPEndPoint endPoint) { if (Client != null && Client.Connected) { throw new InvalidOperationException("Already connected to a server!"); } EndPoint = endPoint; Client = new TcpClient(); Client.Connect(EndPoint); NetworkStream = Client.GetStream(); NetworkManager = new NetworkManager(NetworkStream); NetworkingReset = new ManualResetEvent(true); NetworkWorkerThread = new Thread(NetworkWorker); PhysicsWorkerThread = new Thread(PhysicsWorker); NetworkWorkerThread.Start(); var handshake = new HandshakePacket(NetworkManager.ProtocolVersion, EndPoint.Address.ToString(), (ushort)EndPoint.Port, NetworkMode.Login); SendPacket(handshake); var login = new LoginStartPacket(Session.SelectedProfile.Name); SendPacket(login); PhysicsWorkerThread.Start(); }
private void Handle(Packet pa) { HandshakePacket p = pa as HandshakePacket; if (p.Type == HandshakePacket.SessionType.Server) { Slave sl = new Slave(p, ph); Server.Servers.Add(sl); Console.WriteLine("New Server: " + sl.ToString()); slave = sl; ph.Stream.StreamDisposed += new EventHandler(Stream_StreamDisposed); return; } string[] srvs = new string[Server.Servers.Count]; string[] addrs = new string[Server.Servers.Count]; int[] ports = new int[Server.Servers.Count]; for (int i = 0; i < Server.Servers.Count; i++) { srvs[i] = Server.Servers[i].Name; addrs[i] = Server.Servers[i].Address.ToString(); ports[i] = Server.Servers[i].Port; } Packet.Send(new ServerListPacket { Servers = srvs, Locations = addrs, Ports = ports }, ph.Stream); ph.Stop(); ClientDisconnected(this, EventArgs.Empty); }
private void HandleHandshake(Packet packet) { if (packet is HandshakePacket) { HandshakePacket handshake = (HandshakePacket)packet; ConnectionState = handshake.NextState; } }
public static void HandlePacketHandshake(Client client, HandshakePacket packet) { var usernameHost = Regex.Replace(packet.UsernameAndIpOrHash, Chat.DISALLOWED, "").Split(';'); client.Username = usernameHost[0]; client.Host = usernameHost[1]; client.SendHandshake(); }
private void PerformHandshake() { PacketWriter handshake = HandshakePacket.Handshake(VERSION, Riv, Siv, BLOCK_IV, Type, HANDSHAKE_SIZE); // No encryption for handshake using PoolPacketWriter packet = SendCipher.WriteHeader(handshake.Buffer, 0, handshake.Length); Logger.Debug($"Handshake: {packet}"); SendRaw(packet); }
public async Task Handle(WorldClient client, HandshakePacket packet) { client.SetClientUserID(packet.UserId); _sessionId = client.Id; // Send request to login server and get client key. await _interClient.Send(new ISMessage(ISMessageType.AES_KEY_REQUEST, packet.SessionId)); }
//Handshake. private static async Task HandshakePacketHandler(byte[] data, MemoryStream stream, MinecraftClientConnection connection) { HandshakePacket packet = new HandshakePacket(); await packet.Read(stream); connection.state = packet.nextState; Logger.LogMessage("Handshake with state " + packet.nextState); Logger.LogMessage("IP is " + ((IPEndPoint)connection.client.Client.RemoteEndPoint).Address.ToString()); }
public static void ReadHandshake(Client client, PacketReader reader) { HandshakePacket hp = new HandshakePacket(); hp.Read(reader); if (!reader.Failed) { Client.HandlePacketHandshake(client, hp); } }
private async Task AuthenticateAsync(HandshakePacket handshake, CancellationToken cancellationToken = default) { byte sequenceNumber = 1; bool useSsl = false; if (_options.SslMode != SslMode.DISABLED) { bool sslAvailable = (handshake.ServerCapabilities & (long)CapabilityFlags.SSL) != 0; if (!sslAvailable && _options.SslMode >= SslMode.REQUIRE) { throw new InvalidOperationException("The server doesn't support SSL encryption"); } if (sslAvailable) { var command = new SslRequestCommand(PacketConstants.Utf8Mb4GeneralCi); await _channel.WriteCommandAsync(command, sequenceNumber ++, cancellationToken); _channel.UpgradeToSsl(); useSsl = true; } } var authenticateCommand = new AuthenticateCommand(_options, PacketConstants.Utf8Mb4GeneralCi, handshake.Scramble, handshake.AuthPluginName); await _channel.WriteCommandAsync(authenticateCommand, sequenceNumber, cancellationToken); var packet = await _channel.ReadPacketSlowAsync(cancellationToken); sequenceNumber += 2; ThrowIfErrorPacket(packet, "Authentication error."); if (packet[0] == (byte)ResponseType.Ok) { return; } if (packet[0] == (byte)ResponseType.AuthPluginSwitch) { var body = new ReadOnlySequence <byte>(packet, 1, packet.Length - 1); var switchRequest = new AuthPluginSwitchPacket(body); await HandleAuthPluginSwitch(switchRequest, sequenceNumber, useSsl, cancellationToken); } else { await AuthenticateSha256Async(packet, handshake.Scramble, sequenceNumber, useSsl, cancellationToken); } }
public void Connect() { var endpoint = new IPEndPoint(IPAddress.Parse(config.host), config.port); socket.Connect(endpoint); byte[] buffer = new byte[512]; int count = socket.Receive(buffer); if (count < 512) { writer.Rewrite(); parser.LoadNewBuffer(buffer, count); handshake = new HandshakePacket(); handshake.ParsePacket(parser); this.threadId = handshake.threadId; byte[] token = MakeToken(config.password, GetScrollbleBuffer(handshake.scrambleBuff1, handshake.scrambleBuff2)); writer.IncrementPacketNumber(); //------------------------------------------ authPacket = new ClientAuthenticationPacket(); authPacket.SetValues(config.user, token, config.database, handshake.protocol41); authPacket.WritePacket(writer); byte[] sendBuff = writer.ToArray(); byte[] receiveBuff = new byte[512]; int sendNum = socket.Send(sendBuff); int receiveNum = socket.Receive(receiveBuff); parser.LoadNewBuffer(receiveBuff, receiveNum); if (receiveBuff[4] == 255) { ErrPacket errPacket = new ErrPacket(); errPacket.ParsePacket(parser); return; } else { OkPacket okPacket = new OkPacket(handshake.protocol41); okPacket.ParsePacket(parser); } writer.Rewrite(); GetMaxAllowedPacket(); if (MAX_ALLOWED_PACKET > 0) { writer.SetMaxAllowedPacket(MAX_ALLOWED_PACKET); } } }
private void Background() { var stopTask = task.Task; while (running) { var clientTask = listener.AcceptTcpClientAsync(); if (Task.WaitAny(stopTask, clientTask) == 0) { task = null; return; } var client = clientTask.Result; Task.Run(() => { try { var stream = client.GetStream(); var sel = new PacketSelector(stream); sel.Catch(); if (sel.ID != 0) { return; } var endPoint = (IPEndPoint)client.Client.RemoteEndPoint; var handshake = new HandshakePacket(sel); ServerShadow server; if (servers.ContainsKey(handshake.Address)) { server = servers[handshake.Address]; } else { server = standard; } server.NewConnetcion(handshake, endPoint, stopTask); stream.Close(); } catch (Exception exception) { Log.WriteWarn(exception.Message); } finally { client.Close(); } }); } }
public static IEnumerable <HandshakePacket> GetHandshakes(IEnumerable <TlsRecordPacket> tlsRecordFragments) { using (System.IO.MemoryStream handshakeMessageData = new System.IO.MemoryStream()) { Frame firstFrame = null; foreach (TlsRecordPacket record in tlsRecordFragments) { if (record.ContentType != TlsRecordPacket.ContentTypes.Handshake) { yield break; } foreach (AbstractPacket recordData in record.GetSubPackets(false)) { if (firstFrame == null) { firstFrame = recordData.ParentFrame; } handshakeMessageData.Write(recordData.ParentFrame.Data, recordData.PacketStartIndex, recordData.PacketLength); } } if (handshakeMessageData.Length < 4) //1 byte type, 3 bytes length { yield break; } handshakeMessageData.Position = 1; byte[] lengthBytes = new byte[3]; handshakeMessageData.Read(lengthBytes, 0, 3); uint messageLength = Utils.ByteConverter.ToUInt32(lengthBytes, 0, 3); if (handshakeMessageData.Length < messageLength + 4) { yield break; } handshakeMessageData.Position = 0; Frame reassembledFrame = new Frame(firstFrame.Timestamp, handshakeMessageData.ToArray(), firstFrame.FrameNumber); int nextHandshakeOffset = 0; while (nextHandshakeOffset < reassembledFrame.Data.Length) { HandshakePacket handshake; try { handshake = new HandshakePacket(reassembledFrame, nextHandshakeOffset, reassembledFrame.Data.Length - 1); nextHandshakeOffset = handshake.PacketEndIndex + 1; } catch { yield break; } yield return(handshake); } } }
public void Connect(IPEndPoint endPoint) { if (Client != null && Client.Connected) throw new InvalidOperationException("Already connected to a server!"); EndPoint = endPoint; Client = new TcpClient(); Client.Connect(EndPoint); NetworkStream = Client.GetStream(); Stream = new MinecraftStream(new BufferedStream(NetworkStream)); NetworkWorkerThread = new Thread(NetworkWorker); NetworkWorkerThread.Start(); var handshake = new HandshakePacket(PacketReader.ProtocolVersion, Session.Username, EndPoint.Address.ToString(), EndPoint.Port); SendPacket(handshake); }
public void Handshake(HandshakePacket packet, IRakConnection connection) { if (packet.GameVersion != 171022) { Logger.Warning($"Handshake attempted with client of Game version: {packet.GameVersion}"); return; } const int port = 21836; connection.Send(new HandshakePacket { ConnectionType = Server.Port == port ? 0x01u : 0x04u, Address = Server.GetHost() }); }
public void Parse(IReadable buffer) { // We can assume uncompressed for the time being int packetId = buffer.Reader.ReadVarInt(); // Route the packet by its ID ServerboundPacket packet = null; switch (_Client.ClientState) { case ClientState.Handshaking: switch (packetId) { case 0x00: packet = new HandshakePacket(_Client); break; } break; case ClientState.Status: switch (packetId) { case 0x00: packet = new RequestPacket(_Client); break; case 0x01: packet = new PingPacket(_Client); break; } break; case ClientState.Login: switch (packetId) { case 0x00: packet = new LoginStartPacket(_Client); break; } break; } if (packet != null) { packet.Parse(buffer); // Parse the packet and queue clientbound packets } }
public async Task <ServerStatus> RequestStatus() { var client = new TcpClient(); var task = client.ConnectAsync(ip, port); while (!task.IsCompleted) { Debug.WriteLine("Connecting.."); await Task.Delay(250); } if (!client.Connected) { return(ServerStatus.Empty); } var stream = client.GetStream(); var handshake = new HandshakePacket() { Address = ip, Port = port, LoginState = LoginStates.Status, ProtocolVersion = Program.CurrentProto }; var statusRequest = new Request(); stream.Write(handshake.Stream()); stream.Write(statusRequest.Stream()); var buffer = new byte[Int16.MaxValue]; stream.Read(buffer, 0, buffer.Length); var status = new ResponsePacket(); try { McVarint.TryParse(ref buffer, out int length); McVarint.TryParse(ref buffer, out int packetId); status.Read(buffer); } catch { } return(status.GetStatus()); }
public static void OnGameHandshake(WorldClient client, IPacketStream packet) { var handshake = new HandshakePacket(packet); client.SetClientUserID(handshake.UserId); using var sendPacket = new Packet(PacketType.GAME_HANDSHAKE); sendPacket.Write <byte>(0); client.SendPacket(sendPacket); using var database = DependencyContainer.Instance.Resolve <IDatabase>(); DbUser user = database.Users.Get(handshake.UserId); WorldPacketFactory.SendAccountFaction(client, 2, 0); }
private async Task ConnectAsync(CancellationToken cancellationToken = default) { _channel = new DatabaseConnection(_options); var packet = await _channel.ReadPacketSlowAsync(cancellationToken); ThrowIfErrorPacket(packet, "Initial handshake error."); var handshake = new HandshakePacket(new ReadOnlySequence <byte>(packet)); if (!_allowedAuthPlugins.Contains(handshake.AuthPluginName)) { throw new InvalidOperationException($"Authentication plugin {handshake.AuthPluginName} is not supported."); } _databaseProvider = handshake.ServerVersion.Contains("MariaDB") ? (IDatabaseProvider) new MariaDbProvider() : new MySqlProvider(); await AuthenticateAsync(handshake, cancellationToken); }
/// <summary> /// Handle received packet. /// </summary> /// <param name="packet">Packet data starting with packet id</param> private void InboundPacketHandler(byte[] packet) { switch (packet[0]) { //Save if correct HS was received case HSPid: //Debug.Log("[KSPEthernetIO]: HandshakePacket received"); HandshakePacket HPacket = new HandshakePacket(); HPacket = (HandshakePacket)ByteArrayToStructure(packet, HPacket); _dataReceiveMutex.WaitOne(); //Check hard coded HS values if ((HPacket.M1 == 3) && (HPacket.M2 == 1) && (HPacket.status == 4)) { Debug.Log("[KSPEthernetIO]: Handshake complete"); _handshakeReceived = true; } else { _handshakeReceived = false; } _dataReceiveMutex.ReleaseMutex(); break; //Stack received ControlPackets case Cid: //Debug.Log("[KSPEthernetIO]: ControlPacket received"); _dataReceiveMutex.WaitOne(); if (_cPacketStack.Count < 256 && _enableControl) { ControlPacket cPacket = new ControlPacket(); cPacket = (ControlPacket)ByteArrayToStructure(packet, cPacket); _cPacketStack.Push(cPacket); if (_cPacketStack.Count >= 256) { Debug.LogWarning("[KSPEthernetIO]: ControlPacket buffer overflow!"); } } _dataReceiveMutex.ReleaseMutex(); break; default: Debug.LogWarning("[KSPEthernetIO]: Packet ID " + packet[0] + " unknown"); break; } }
public void Connect(IPEndPoint endPoint) { if (Client != null && Client.Connected) { throw new InvalidOperationException("Already connected to a server!"); } EndPoint = endPoint; Client = new TcpClient(); Client.Connect(EndPoint); NetworkStream = Client.GetStream(); Stream = new MinecraftStream(new BufferedStream(NetworkStream)); NetworkWorkerThread = new Thread(NetworkWorker); NetworkWorkerThread.Start(); var handshake = new HandshakePacket(PacketReader.ProtocolVersion, Session.Username, EndPoint.Address.ToString(), EndPoint.Port); SendPacket(handshake); }
public static void OnGameHandshake(WorldClient client, IPacketStream packet) { var handshake = new HandshakePacket(packet); client.SetClientUserID(handshake.UserId); using var sendPacket = new Packet(PacketType.GAME_HANDSHAKE); sendPacket.Write(0); client.SendPacket(sendPacket); using var database = DependencyContainer.Instance.Resolve <IDatabase>(); DbUser user = database.Users.Include(u => u.Characters).Where(u => u.Id == handshake.UserId).FirstOrDefault(); WorldPacketFactory.SendCharacterList(client, user.Characters); WorldPacketFactory.SendAccountFaction(client, user); }
public void HandleHandshake(HandshakePacket packet, Connection connection) { if (packet.ClientVersion != 130529) { Logger.Warning($"{connection.EndPoint} connected with false game version: {packet.ClientVersion}"); return; } Logger.Information($"Handshaking with {connection.EndPoint}"); connection.Send(new HandshakePacket { NewConnectionType = Server.Port == 1001 ? ConnectionType.Authentication : ConnectionType.World, Port = packet.Port, ProcessId = (uint)Process.GetCurrentProcess().Id, Ip = "127.0.0.1" }); }
public void Handshake(HandshakePacket packet, IRakConnection connection) { if (packet == null) { throw new ArgumentNullException(nameof(packet), ResourceStrings.GeneralHandler_Handshake_PacketNullException); } if (packet.GameVersion != 171022) { Logger.Warning($"Handshake attempted with client of Game version: {packet.GameVersion}"); } connection.Send(new HandshakePacket { ConnectionType = UchuServer.Port == UchuServer.Config.Networking.AuthenticationPort ? 0x01u : 0x04u, Address = UchuServer.Host }); }
public void Handshake(HandshakePacket packet, IRakConnection connection) { if (packet == null) { throw new ArgumentNullException(nameof(packet), ResourceStrings.GeneralHandler_Handshake_PacketNullException); } if (packet.GameVersion != 171022) { Logger.Warning($"Handshake attempted with client of Game version: {packet.GameVersion}"); } // TODO: Use resource / setting const int port = 21836; connection.Send(new HandshakePacket { ConnectionType = UchuServer.Port == port ? 0x01u : 0x04u, Address = UchuServer.Host }); }
public void TestDecode() { HexData samplePacket = new HexData("e4ff0000171116b9c8c2eb9a0c815d415be8bda522edfa145e1178e63dd8e8da9f9c637dd95b03413c82cd8c408e6f9722022f02eeb44626382118e6c9e0cb7df0099dbe936a71f0dbe85e4dd445d11f7cd46fa0f21d3972574164ed409c03a56f8585891a18652bd7682914647f4ce42c6fef68161e4a3321a870e369edccdfcc130a88f6f4b5e33d820dcc996db5d7cc775b29bf2f34cdd23d906f2d386026c4ce002dfdd227bc0fcee14a8089278e4e59c36ecc549c4f399b8c08"); byte[] bytes = samplePacket.bytes; Packet p = Packet.Unpack(samplePacket.bytes); Assert.AreEqual(p.GetType(), typeof(HandshakePacket)); HandshakePacket recP = p as HandshakePacket; Assert.AreEqual(0xff000017, recP.Version); Assert.AreEqual((UInt32)17, recP.DCIDLength); CollectionAssert.AreEqual((new HexData("16b9c8c2eb9a0c815d415be8bda522edfa")).bytes, recP.DCID); Assert.AreEqual((UInt32)20, recP.SCIDLength); CollectionAssert.AreEqual((new HexData("5e1178e63dd8e8da9f9c637dd95b03413c82cd8c")).bytes, recP.SCID); // PacketNumberLength and PacketNumber cannot be computed correctly: see TestInitialPacket // Assert.AreEqual((UInt32)1, recP.PacketNumberLength); // Assert.AreEqual((UInt32)111, recP.PacketNumber); Assert.AreEqual((UInt64)142, recP.Length.Value); CollectionAssert.AreEqual((new HexData("9722022f02eeb44626382118e6c9e0cb7df0099dbe936a71f0dbe85e4dd445d11f7cd46fa0f21d3972574164ed409c03a56f8585891a18652bd7682914647f4ce42c6fef68161e4a3321a870e369edccdfcc130a88f6f4b5e33d820dcc996db5d7cc775b29bf2f34cdd23d906f2d386026c4ce002dfdd227bc0fcee14a8089278e4e59c36ecc549c4f399b8c08")).bytes, recP.Payload); }