private void AssertPackage <T>(PPPokerPackage package, CapturedPacket capturedPacket) { Assert.IsTrue( SerializationHelper.TryDeserialize(package.Body, out T packageContent), $"Failed to deserialize {typeof(T)} package [ticks={capturedPacket.CreatedTimeStamp.Ticks}, userid={package.ClientPort}]" ); }
private void LogPacket(CapturedPacket capturedPacket, string ext) { var packageFileName = Path.Combine("Logs", capturedPacket.ToString().Replace(":", ".").Replace("->", "-")) + ext; var packetManager = new Adda52PacketManager(); var sb = new StringBuilder(); sb.AppendLine("-----------begin----------------"); sb.AppendLine($"Date: {capturedPacket.CreatedTimeStamp}"); sb.AppendLine($"Date Now: {DateTime.Now}"); sb.AppendLine($"Date Now (ticks): {DateTime.Now.Ticks}"); sb.AppendLine($"SequenceNumber: {capturedPacket.SequenceNumber}"); sb.AppendLine($"Packet Full Length: {(packetManager.IsStartingPacket(capturedPacket.Bytes) ? packetManager.ReadPacketLength(capturedPacket.Bytes) : 0)}"); sb.AppendLine($"Packet Current Length: {capturedPacket.Bytes.Length}"); sb.AppendLine($"Body:"); sb.AppendLine("---------body begin-------------"); sb.AppendLine(BitConverter.ToString(capturedPacket.Bytes).Replace("-", " ")); sb.AppendLine("----------body end--------------"); sb.AppendLine("---------text body begin-------------"); sb.AppendLine(Encoding.UTF8.GetString(capturedPacket.Bytes)); sb.AppendLine("----------text body end--------------"); sb.AppendLine("------------end-----------------"); File.AppendAllText(packageFileName, sb.ToString()); }
public CapturedPacketAdvanced(CapturedPacket capturedPacket) { Bytes = capturedPacket.Bytes; Source = capturedPacket.Source; Destination = capturedPacket.Destination; CreatedTimeStamp = capturedPacket.CreatedTimeStamp; SequenceNumber = capturedPacket.SequenceNumber; }
protected override void LogPacket(CapturedPacket capturedPacket, string ext) { var packet = capturedPacket as CapturedPacketAdvanced; packet.ProcessedTime = DateTime.Now; if (packet.ProcessedTime - packet.BufferedTime > TimeSpan.FromSeconds(30)) { Debug.WriteLine($"Packet {capturedPacket}, processed time: {packet.ProcessedTime - packet.BufferedTime}"); } }
public void AddPacket(CapturedPacket capturedPacket) { unchecked { sequenceNumber++; } capturedPacket.SequenceNumber = sequenceNumber; packetBuffer.Add(capturedPacket); }
static string GetSessionName(CapturedPacket capPacket) { if (capPacket.LocalEndPoint != null && capPacket.RemoteEndPoint != null) { return($"{capPacket.Protocol.ToString().Substring(0, 1)} :{ capPacket.LocalEndPoint.Port } → {capPacket.RemoteEndPoint}"); } else { return($"0x{capPacket.Handle:X8}"); } }
public void LogPackage(CapturedPacket capturedPacket, PPPokerPackage package) { if (!loggers.TryGetValue(package.ClientPort, out DebugPPPLogger logger)) { logger = new DebugPPPLogger(package.ClientPort); loggers.Add(package.ClientPort, logger); } protectedLogger = logger; base.LogPackage(package); }
public void TryParsePacketTest(string file) { var bytes = ReadPacketFile(file); var packetManager = new PokerMasterPacketManager(); var capturedPacket = new CapturedPacket { Bytes = bytes, CreatedTimeStamp = DateTime.Parse("08/02/2018 12:28:28"), Destination = new IPEndPoint(IPAddress.Parse("192.168.0.105"), 27633), Source = new IPEndPoint(IPAddress.Parse("47.52.92.161"), 9188), SequenceNumber = 1962805251 }; var dumpFiles = Directory.GetFiles(@"d:\Temp\Dump\", "*.*", SearchOption.TopDirectoryOnly); var sqNo = 1u; foreach (var dumpFile in dumpFiles) { var dumpCaptPack = new CapturedPacket { Bytes = File.ReadAllBytes(dumpFile).Skip(25).ToArray(), CreatedTimeStamp = DateTime.Parse("08/02/2018 12:28:28"), Destination = new IPEndPoint(IPAddress.Parse("192.168.0.105"), 27633), Source = new IPEndPoint(IPAddress.Parse("47.52.92.161"), 9188), SequenceNumber = sqNo++ }; if (packetManager.TryParse(dumpCaptPack, out IList <PokerMasterPackage> dumpPacks)) { var dmpPack = dumpPacks.FirstOrDefault(); if (dmpPack.Cmd == PackageCommand.Cmd_SCLoginRsp) { var bodyDecryptor = new BodyDecryptor(); var key = Encoding.UTF8.GetBytes("116ff58c0b178429"); var bodyBytes = bodyDecryptor.Decrypt(dmpPack.Body, key, false); File.WriteAllBytes(@"d:\dmp.bin", bodyBytes); } } } var result = packetManager.TryParse(capturedPacket, out IList <PokerMasterPackage> actualPackages); Assert.IsTrue(result); Assert.IsNotNull(actualPackages); CollectionAssert.IsNotEmpty(actualPackages); }
public void LogPackage(CapturedPacket capturedPacket, PokerKingPackage package) { var port = destinationPorts.Contains(capturedPacket.Destination.Port) ? capturedPacket.Destination.Port : capturedPacket.Source.Port; if (!loggers.TryGetValue(port, out DebugPKLogger logger)) { logger = new DebugPKLogger(port); loggers.Add(port, logger); } protectedLogger = logger; base.LogPackage(package); }
public void DeserializationTest(string file, string jsonFile) { var bytes = ReadPacketFile(file); var packetManager = new PPPokerPacketManager(); var capturedPacket = new CapturedPacket { Bytes = bytes, CreatedTimeStamp = DateTime.Parse("08/02/2018 12:28:28"), Destination = new IPEndPoint(IPAddress.Parse("192.168.0.105"), 27633), Source = new IPEndPoint(IPAddress.Parse("47.52.92.161"), 4000), SequenceNumber = 1962805251 }; var result = packetManager.TryParse(capturedPacket, out IList <PPPokerPackage> packages); foreach (var package in packages) { object actual = null; switch (package.PackageType) { case PackageType.EnterRoomRSP: actual = SerializationHelper.Deserialize <EnterRoomRSP>(package.Body); break; case PackageType.SitDownBRC: actual = SerializationHelper.Deserialize <SitDownBRC>(package.Body); break; case PackageType.DealerInfoRSP: actual = SerializationHelper.Deserialize <DealerInfoRSP>(package.Body); break; case PackageType.ActionBRC: actual = SerializationHelper.Deserialize <ActionBRC>(package.Body); break; case PackageType.WinnerRSP: actual = SerializationHelper.Deserialize <WinnerRSP>(package.Body); break; } var jsonExpected = File.ReadAllText(Path.Combine(TestDataFolder, jsonFile)); var jsonActual = JsonConvert.SerializeObject(actual, Formatting.Indented, new StringEnumConverter()); Assert.That(jsonActual, Is.EqualTo(jsonExpected)); } }
public void DeserializationTest(string file, string jsonFile) { var bytes = ReadPacketFile(file); var packetManager = new PokerKingPacketManager(); var capturedPacket = new CapturedPacket { Bytes = bytes, CreatedTimeStamp = DateTime.Parse("08/02/2018 12:28:28"), Destination = new IPEndPoint(IPAddress.Parse("192.168.0.105"), 27633), Source = new IPEndPoint(IPAddress.Parse("47.52.92.161"), 9188), SequenceNumber = 1962805251 }; var result = packetManager.TryParse(capturedPacket, out IList <PokerKingPackage> packages); foreach (var package in packages) { object actual = null; switch (package.PackageType) { case PackageType.NoticeGameRoundEnd: actual = SerializationHelper.Deserialize <NoticeGameRoundEnd>(package.Body); break; case PackageType.NoticePlayerActionTurn: actual = SerializationHelper.Deserialize <NoticePlayerActionTurn>(package.Body); break; case PackageType.NoticeGameSnapShot: actual = SerializationHelper.Deserialize <NoticeGameSnapShot>(package.Body); break; case PackageType.NoticePlayerAction: actual = SerializationHelper.Deserialize <NoticePlayerAction>(package.Body); break; case PackageType.RequestJoinRoom: actual = SerializationHelper.Deserialize <RequestJoinRoom>(package.Body); break; } var jsonExpected = File.ReadAllText(Path.Combine(TestDataFolder, jsonFile)); var jsonActual = JsonConvert.SerializeObject(actual, Formatting.Indented, new StringEnumConverter()); Assert.That(jsonActual, Is.EqualTo(jsonExpected)); } }
public override bool TryParse(CapturedPacket capturedPacket, out IList <PPPokerPackage> packages) { bool result = base.TryParse(capturedPacket, out packages); // Packages don't contain any client application ID, we're going to use client port for this var direction = capturedPacket.Source.Port == PPPConstants.Port ? PackageDirection.Incoming : PackageDirection.Outgoing; var clientPort = direction == PackageDirection.Incoming ? capturedPacket.Destination.Port : capturedPacket.Source.Port; foreach (var package in packages) { package.Direction = direction; package.ClientPort = clientPort; } return(result); }
// Store packet to be sent to all attached analyzers. // Packets are only sent IF the InitialiseHandshake(..) has been called. // It's allowed to 'send' packets before the handshake is initialised. public void SendPacket(PacketType type, PacketDirection direction, uint bodyTypeHash, byte[] data) { // Construct new payload to send. var packet = new CapturedPacket() { Type = type, Direction = direction, Data = ByteString.CopyFrom(data, 0, data.Length), BodyTypeHash = bodyTypeHash, PassedSeconds = Duration.FromTimeSpan(_timeWatch.Elapsed) }; // Write length delimited payload. var tempBuffer = new MemoryStream(); packet.WriteDelimitedTo(tempBuffer); byte[] packetBytes = tempBuffer.ToArray(); Socket[] connectionsCopy; lock (_bufferLock) { // Append data to the replay buffer. _replayBuffer.Write(packetBytes, 0, packetBytes.Length); // Race conditions occur when a copy isn't made. connectionsCopy = _connections.ToArray(); } // Trigger a send of new data on all analyzer connections. foreach (Socket connection in connectionsCopy) { try { connection.BeginSend(packetBytes, 0, packetBytes.Length, SocketFlags.None, FinishSocketSend, connection); } catch (Exception e) { string message = string.Format("Sending data to analyzer caused exception `{0}`, connection is closed!", e.Message); HookRegistry.Get().Log(message); CleanSocket(connection); } } }
public void TryParsePacketTest(string file, int expected) { var bytes = ReadPacketFile(file); var packetManager = new PPPokerPacketManager(); var capturedPacket = new CapturedPacket { Bytes = bytes, CreatedTimeStamp = DateTime.Parse("08/02/2018 12:28:28"), Destination = new IPEndPoint(IPAddress.Parse("192.168.0.105"), 27633), Source = new IPEndPoint(IPAddress.Parse("47.52.92.161"), 4000), SequenceNumber = 1962805251 }; var result = packetManager.TryParse(capturedPacket, out IList <PPPokerPackage> actualPackages); Assert.IsTrue(result); Assert.IsNotNull(actualPackages); Assert.That(actualPackages.Count, Is.EqualTo(expected)); }
private async Task OnBeforeRequest(object sender, SessionEventArgs e) { if (e.WebSession == null || e.WebSession.Request == null) { return; } var importer = importers.FirstOrDefault(x => !x.IsDisabled() && x.IsRunning && x.IsMatch(e.WebSession.Request)); if (importer == null) { return; } // remove compression e.WebSession.Request.Headers.RemoveHeader("Sec-WebSocket-Extensions"); await Task.Run(() => { e.DataReceived += (s, a) => { if (a.Count == 0) { return; } var capturedPacket = new CapturedPacket { Bytes = a.Buffer.Take(a.Count).ToArray(), CreatedTimeStamp = DateTime.UtcNow, Source = new IPEndPoint(IPAddress.Any, e.WebSession.Request.RequestUri.Port), Destination = e.ClientEndPoint }; importer.AddPacket(capturedPacket); }; }); }
//[TestCase(@"d:\Git\Temp\PKLogs\")] public void TestPerformance(string logPath) { var logs = Directory.GetFiles(logPath, "*-*.*.log"); var capturedPackets = new List <CapturedPacketAdvanced>(); foreach (var log in logs) { capturedPackets.AddRange(TcpImporterTestUtils.ReadCapturedPackets(log, "yyyy/M/d dddd tt H:mm:ss", true).Select(x => new CapturedPacketAdvanced(x))); } CollectionAssert.IsNotEmpty(capturedPackets); capturedPackets = capturedPackets.OrderBy(x => x.CreatedTimeStamp).ToList(); var importer = new PKTestImporter(); importer.Start(); CapturedPacket previousCapturedPacket = null; foreach (var capturedPacket in capturedPackets) { if (previousCapturedPacket != null) { var delay = capturedPacket.CreatedTimeStamp - previousCapturedPacket.CreatedTimeStamp; Task.Delay(delay).Wait(); } capturedPacket.BufferedTime = DateTime.Now; importer.AddPacket(capturedPacket); previousCapturedPacket = capturedPacket; } importer.Stop(); }
private void AssertPackage(PPPokerPackage package, CapturedPacket capturedPacket) { switch (package.PackageType) { case PackageType.GetUserMarksREQ: AssertPackage <GetUserMarksREQ>(package, capturedPacket); break; case PackageType.GetUserMarksRSP: AssertPackage <GetUserMarksRSP>(package, capturedPacket); break; case PackageType.SelUserInfoRSP: AssertPackage <SelUserInfoRSP>(package, capturedPacket); break; case PackageType.EnterRoomRSP: AssertPackage <EnterRoomRSP>(package, capturedPacket); break; case PackageType.SitDownRSP: AssertPackage <SitDownRSP>(package, capturedPacket); break; case PackageType.SitDownBRC: AssertPackage <SitDownBRC>(package, capturedPacket); break; case PackageType.StandUpBRC: AssertPackage <StandUpBRC>(package, capturedPacket); break; case PackageType.BlindStatusBRC: AssertPackage <BlindStatusBRC>(package, capturedPacket); break; case PackageType.DealerInfoRSP: AssertPackage <DealerInfoRSP>(package, capturedPacket); break; case PackageType.RoundStartBRC: AssertPackage <RoundStartBRC>(package, capturedPacket); break; case PackageType.RoundOverBRC: AssertPackage <RoundOverBRC>(package, capturedPacket); break; case PackageType.ActionBRC: AssertPackage <ActionBRC>(package, capturedPacket); break; case PackageType.HandCardRSP: AssertPackage <HandCardRSP>(package, capturedPacket); break; case PackageType.ShowHandRSP: AssertPackage <ShowHandRSP>(package, capturedPacket); break; case PackageType.WinnerRSP: AssertPackage <WinnerRSP>(package, capturedPacket); break; case PackageType.ShowMyCardBRC: AssertPackage <ShowMyCardBRC>(package, capturedPacket); break; case PackageType.UserSngOverRSP: AssertPackage <UserSngOverRSP>(package, capturedPacket); break; case PackageType.TableGameOverRSP: AssertPackage <TableGameOverRSP>(package, capturedPacket); break; case PackageType.LeaveRoomRSP: AssertPackage <LeaveRoomRSP>(package, capturedPacket); break; } }
public override void AddPacket(CapturedPacket capturedPacket) { packetBuffer.Add(capturedPacket); }
private void AssertPackage(PokerKingPackage package, CapturedPacket capturedPacket) { switch (package.PackageType) { case PackageType.RequestLeaveRoom: AssertPackage <RequestLeaveRoom>(package, capturedPacket); break; case PackageType.NoticeStartGame: AssertPackage <NoticeStartGame>(package, capturedPacket); break; case PackageType.NoticeResetGame: AssertPackage <NoticeResetGame>(package, capturedPacket); break; case PackageType.NoticeGamePost: AssertPackage <NoticeGamePost>(package, capturedPacket); break; case PackageType.NoticeGameAnte: AssertPackage <NoticeGameAnte>(package, capturedPacket); break; case PackageType.NoticeGameElectDealer: AssertPackage <NoticeGameElectDealer>(package, capturedPacket); break; case PackageType.NoticeGameBlind: AssertPackage <NoticeGameBlind>(package, capturedPacket); break; case PackageType.NoticeGameHoleCard: AssertPackage <NoticeGameHoleCard>(package, capturedPacket); break; case PackageType.NoticePlayerAction: AssertPackage <NoticePlayerAction>(package, capturedPacket); break; case PackageType.NoticeGameRoundEnd: AssertPackage <NoticeGameRoundEnd>(package, capturedPacket); break; case PackageType.NoticeGameCommunityCards: AssertPackage <NoticeGameCommunityCards>(package, capturedPacket); break; case PackageType.NoticeGameShowCard: AssertPackage <NoticeGameShowCard>(package, capturedPacket); break; case PackageType.NoticeGameSettlement: AssertPackage <NoticeGameSettlement>(package, capturedPacket); break; case PackageType.NoticeGameShowDown: AssertPackage <NoticeGameShowDown>(package, capturedPacket); break; case PackageType.NoticePlayerStayPosition: AssertPackage <NoticePlayerStayPosition>(package, capturedPacket); break; case PackageType.NoticePlayerShowCard: AssertPackage <NoticePlayerShowCard>(package, capturedPacket); break; case PackageType.NoticeBuyin: AssertPackage <NoticeBuyin>(package, capturedPacket); break; case PackageType.NoticeGameSnapShot: AssertPackage <NoticeGameSnapShot>(package, capturedPacket); break; case PackageType.RequestHeartBeat: AssertPackage <RequestHeartBeat>(package, capturedPacket); break; case PackageType.NoticeQuickLeave: AssertPackage <NoticeQuickLeave>(package, capturedPacket); break; case PackageType.RequestQuickFold: AssertPackage <RequestQuickFold>(package, capturedPacket); break; } }
public static List <CapturedPacket> ReadCapturedPackets(string file, string dateFormat, bool usePacketDate = false) { FileAssert.Exists(file); var sourceDestination = ParseSourceDestinationFromFile(Path.GetFileNameWithoutExtension(file)); var lines = File.ReadAllLines(file); var capturedPackets = new List <CapturedPacket>(); CapturedPacket capturedPacket = null; bool isBody = false; foreach (var line in lines) { if (line.IndexOf("-begin-") > 0) { capturedPacket = new CapturedPacket { Source = new IPEndPoint(IPAddress.Parse(sourceDestination.Item1), sourceDestination.Item2), Destination = new IPEndPoint(IPAddress.Parse(sourceDestination.Item3), sourceDestination.Item4), }; continue; } if (!string.IsNullOrEmpty(dateFormat) && line.StartsWith("Date:", StringComparison.OrdinalIgnoreCase)) { var dateText = line.Substring(5).Trim(); capturedPacket.CreatedTimeStamp = DateTime.ParseExact(dateText, dateFormat, null); continue; } if (!usePacketDate && line.StartsWith("Date Now (ticks):", StringComparison.OrdinalIgnoreCase)) { var ticksText = line.Substring(17).Trim(); var ticks = long.Parse(ticksText); capturedPacket.CreatedTimeStamp = new DateTime(ticks); continue; } if (line.StartsWith("SequenceNumber:", StringComparison.OrdinalIgnoreCase)) { var sequenceNumberText = line.Substring(16).Trim(); capturedPacket.SequenceNumber = uint.Parse(sequenceNumberText); continue; } if (line.IndexOf("-body begin-") > 0) { isBody = true; continue; } if (line.IndexOf("-body end-") > 0) { isBody = false; continue; } if (isBody) { capturedPacket.Bytes = line.FromHexStringToBytes(); } if (line.IndexOf("-end-") > 0 && capturedPacket != null) { capturedPackets.Add(capturedPacket); } } var packetsToUpdate = capturedPackets.GroupBy(x => x.CreatedTimeStamp) .Select(x => new { Date = x.Key, Packets = x.ToList() }) .Where(x => x.Packets.Count > 1) .ToArray(); packetsToUpdate.ForEach(x => { var delta = 0; x.Packets.ForEach(y => y.CreatedTimeStamp = y.CreatedTimeStamp.AddTicks(delta++)); }); return(capturedPackets); }
void NewCapturedPacked(CapturedPacket capPacket) { var isNew = !ChildrenSessions.ContainsKey(capPacket.Handle); if (isNew && capPacket.Event == MonitorEvent.Close) { return; // ignore unknown closed sockets } var sessionItem = GetChild(capPacket.Handle); if (capPacket.Error != SocketError.Success) { Log(sessionItem.ChildSession, new SocketException((int)capPacket.Error).Message, MessageType.Error); } if (isNew || (capPacket.Event == MonitorEvent.Connected && capPacket.Error == SocketError.Success)) { sessionItem.ChildSession.Name = GetSessionName(capPacket); } switch (capPacket.Event) { case MonitorEvent.Send: case MonitorEvent.SendTo: case MonitorEvent.Recv: case MonitorEvent.RecvFrom: var packet = new Packet() { Payload = capPacket.Data, Source = (IPEndPoint)socket.LocalEndPoint, Destination = (IPEndPoint)socket.RemoteEndPoint, Flow = GetTrafficFlow(capPacket.Event) }; sessionItem.Mediator.Send(packet); break; case MonitorEvent.Connecting: if (!isNew) { break; // can be observed multiple times on non-blocking socket without any Connected event } Log(sessionItem.ChildSession, $"Connecting to {capPacket.Protocol.ToString().ToLower()}://{capPacket.RemoteEndPoint}"); break; case MonitorEvent.Connected: // dump socket info break; case MonitorEvent.Accepted: Log(sessionItem.ChildSession, $"Accepted from {capPacket.Protocol.ToString().ToLower()}://{capPacket.RemoteEndPoint}"); break; case MonitorEvent.Listen: Log(sessionItem.ChildSession, $"Starting listener at {capPacket.LocalEndPoint}"); break; case MonitorEvent.Close: Log(sessionItem.ChildSession, $"Socket closed", MessageType.Error); break; } }