/// <summary> /// https://www.geeksforgeeks.org/tcp-flags/?ref=lbp /// </summary> /// <param name="tcp"></param> /// <returns></returns> private string GetFlags(TcpDatagram tcp) { string flags = ""; if (tcp.IsAcknowledgment) { flags += " ACK "; } if (tcp.IsFin) { flags += " FIN "; } if (tcp.IsSynchronize) { flags += " SYN "; } if (tcp.IsReset) { flags += " RST "; } if (tcp.IsPush) { flags += " PSH "; } if (tcp.IsUrgent) // Gói khẩn cấp { flags += " URG "; } return(flags.Replace(" ", ", ").Trim()); }
private void ProceedResponce(Packet responce) { IpV4Datagram ipDatagram = responce.Ethernet.IpV4; TcpDatagram tcpDatagram = ipDatagram.Tcp; TcpControlBits bits = tcpDatagram.ControlBits; bool isSyn = bits.HasFlag(TcpControlBits.Synchronize) && !bits.HasFlag(TcpControlBits.Acknowledgment); if (!isSyn) { return; } if (this.attempts.ContainsKey(ipDatagram.Source)) { this.attempts[ipDatagram.Source]++; } else { this.attempts.Add(ipDatagram.Source, 1); } Console.WriteLine("{0}:{1} is trying to connect {2}:{3}.", ipDatagram.Source, tcpDatagram.SourcePort, ipDatagram.Destination, tcpDatagram.DestinationPort ); this.CheckConnections(); }
private void PacketHandler(Packet packet) { // print timestamp and length of the packet // Console.WriteLine(packet.Timestamp.ToString("yyyy-MM-dd hh:mm:ss.fff") + " length:" + packet.Length); ip = packet.Ethernet.IpV4; udp = ip.Udp; tcp = ip.Tcp; if (ip != null) { // System.Windows.Forms.Form.CheckForIllegalCrossThreadCalls = false; Thread.Sleep(300); ListViewItem item = new ListViewItem(ip.Source.ToString()); item.SubItems.Add(ip.Destination.ToString()); item.SubItems.Add(packet.Timestamp.ToString("yyyy-MM-dd hh:mm:ss.fff")); item.SubItems.Add(packet.Length.ToString()); item.SubItems.Add(ip.Protocol.ToString()); listView1.Items.Add(item); paketler.Add(k, packet); k++; } // print ip addresses and udp ports // Console.WriteLine(ip.Source + ":" + udp.SourcePort + " -> " + ip.Destination + ":" + udp.DestinationPort); }
protected override bool CalculateIsValid() { if (!base.CalculateIsValid()) { return(false); } IpV4Datagram ipV4 = this.IpV4; if ((int)this.Code == 4) { return(ipV4.Length == 256); } switch (ipV4.Protocol) { case IpV4Protocol.Tcp: TcpDatagram tcp = ipV4.Tcp; if (tcp.Length >= 20) { return(tcp.Length >= tcp.HeaderLength); } return(false); case IpV4Protocol.Udp: return(ipV4.Udp.Length >= 8); default: return(true); } }
public TcpConnection(Packet packet) { if (packet.Ethernet == null) { throw new Exception("error creating TcpStreamAddress packet is not ethernet"); } EthernetDatagram ethernet = packet.Ethernet; //if (ip == null) if (ethernet.EtherType != PcapDotNet.Packets.Ethernet.EthernetType.IpV4) { throw new Exception("error creating TcpStreamAddress packet is not ipv4"); } IpV4Datagram ip = ethernet.IpV4; //if (tcp == null) if (ip.Protocol != IpV4Protocol.Tcp) { throw new Exception("error creating TcpStreamAddress packet is not tcp"); } TcpDatagram tcp = ip.Tcp; //_source = new TcpAddress(ip.Source, tcp.SourcePort); _source = new TcpAddress(ethernet.Source, ip.Source, tcp.SourcePort); //_destination = new TcpAddress(ip.Destination, tcp.DestinationPort); _destination = new TcpAddress(ethernet.Destination, ip.Destination, tcp.DestinationPort); SetOrder(); }
/// <summary> /// Valid if the datagram's length is OK, the checksum is correct, the code is in the expected range /// and the IPv4 payload contains at least an IPv4 header and the transport header. /// If the code is for unsupported transport protocol, the IPv4 payload should contain 256 bytes of the original datagram. /// </summary> protected override bool CalculateIsValid() { if (!base.CalculateIsValid()) { return(false); } IpV4Datagram ip = IpV4; if ((IcmpCodeConversionFailed)Code == IcmpCodeConversionFailed.UnsupportedTransportProtocol) { return(ip.Length == OriginalDatagramLengthForUnsupportedTransportProtocol); } switch (ip.Protocol) { case IpV4Protocol.Udp: return(ip.Udp.Length >= UdpDatagram.HeaderLength); case IpV4Protocol.Tcp: TcpDatagram tcp = ip.Tcp; return(tcp.Length >= TcpDatagram.HeaderMinimumLength && tcp.Length >= tcp.HeaderLength); default: // Todo: support more protocols return(true); } }
public void HandlePacket(IPacketProducer source, Packet packet) { IpV4Datagram ip = packet.Ethernet.IpV4; TcpDatagram tcp = ip.Tcp; var msg = new StringBuilder(); msg.Append(packet.Timestamp.ToString("hh:mm:ss.fff")); msg.Append(" (").Append(packet.Length).Append(") "); if (tcp.IsValid) { msg.Append(ip.Source).Append(":").Append(tcp.SourcePort).Append(" -> "); msg.Append(ip.Destination).Append(":").Append(tcp.DestinationPort).Append(' '); if (tcp.Http.IsRequest && ((HttpRequestDatagram)tcp.Http).Method != null) { var http = (HttpRequestDatagram)tcp.Http; msg.Append(http.Method?.Method ?? "???").Append(' ').Append(http.Uri).Append(' ').Append(http.Version); } else if (tcp.Http.IsResponse) { var http = (HttpResponseDatagram)tcp.Http; msg.Append(http.StatusCode).Append(' ').Append(http.ReasonPhrase); } } else { msg.Append(ip.Source).Append(" -> ").Append(ip.Destination); } Console.WriteLine(msg); }
public PPacket(Packet packet, long packetNumber, TimeSpan relativeTime) { _packet = packet; _packetNumber = packetNumber; _relativeTime = relativeTime; EthernetDatagram ethernet = packet.Ethernet; if (ethernet != null) { _ethernetType = ethernet.EtherType; _ethernetTypeCode = GetEthernetTypeCode(ethernet.EtherType); //_ipv4 = packet.Ethernet.IpV4; //if (_ipv4 != null) if (ethernet.EtherType == PcapDotNet.Packets.Ethernet.EthernetType.IpV4) { _ipv4 = packet.Ethernet.IpV4; _source = _ipv4.Source; _destination = _ipv4.Destination; _ipProtocol = _ipv4.Protocol; _ipProtocolCode = GetIPProtocolCode(_ipv4.Protocol); //_tcp = _ipv4.Tcp; //if (_tcp != null) if (_ipv4.Protocol == IpV4Protocol.Tcp) { _tcp = _ipv4.Tcp; _sourcePort = _tcp.SourcePort; _destinationPort = _tcp.DestinationPort; } } } }
public PacketClass(TcpDatagram tcp, bool inc, PacketInfo.Daemon daemon, ushort port) { Tcp = tcp; IsIncoming = inc; Daemon = daemon; Port = port; }
public A3Packet(Packet packet, TcpDatagram tcp, bool inc, ushort port) { this.Packet = packet; this.Tcp = tcp; this.IsIncoming = inc; this.Port = port; this.Timestamp = Utils.GetEpochTime(); }
/// <summary> /// Handle IPV4 packets, including TCP and UDP packets /// </summary> /// <param name="packet">The IpV4Datagram to parse</param> public static void HandleIPV4(Packet packet, IpV4Datagram ip, ref UInt64 frame_id, object[] ctrl) { ListViewItem item = new ListViewItem(frame_id.ToString()); frame_id++; List <string> packet_info = new List <string>(); ListView frames = (ListView)ctrl[0]; EthernetDatagram ethernet = packet.Ethernet; switch (ip.Protocol) { case IpV4Protocol.Udp: { UdpDatagram udp = ip.Udp; packet_info.Add(packet.Timestamp.ToString("hh:mm:ss.fff tt")); packet_info.Add(ip.Source + ":" + udp.SourcePort); packet_info.Add(ip.Destination + ":" + udp.DestinationPort); packet_info.Add(ethernet.Source.ToString()); packet_info.Add(ethernet.Destination.ToString()); packet_info.Add("UDP"); packet_info.Add(udp.Length.ToString()); break; } case IpV4Protocol.Tcp: { TcpDatagram tcp = ip.Tcp; packet_info.Add(packet.Timestamp.ToString("hh:mm:ss.fff tt")); packet_info.Add(ip.Source + ":" + tcp.SourcePort); packet_info.Add(ip.Destination + ":" + tcp.DestinationPort); packet_info.Add(ethernet.Source.ToString()); packet_info.Add(ethernet.Destination.ToString()); packet_info.Add("TCP"); packet_info.Add(tcp.Length.ToString()); break; } default: { item = null; break; } } // update UI if (item != null) { item.SubItems.AddRange(packet_info.ToArray()); object[] param = new object[2]; param[0] = frames; object[] o = new object[3]; o[0] = item; o[1] = ctrl[1]; o[2] = packet; param[1] = o; frames.BeginInvoke(new ParserHelper.UIHandlerEx(ParserHelper.UpdateFrameUI), param); } }
private static void PacketHandler(Packet packet) { IpV4Datagram ip = packet.Ethernet.IpV4; TcpDatagram tcp = ip.Tcp; if (/*ip.Destination.ToString() == "192.168.43.1" ||*/ ip.Source.ToString() == "192.168.43.1") { Console.WriteLine("#PACKET:"); Console.WriteLine("SYN ?:" + tcp.IsSynchronize); Console.WriteLine("ACK ?:" + tcp.IsAcknowledgment); Console.WriteLine("FIN ?:" + tcp.IsFin); Console.WriteLine("PUSH ?:" + tcp.IsPush); Console.WriteLine(packet.Timestamp.ToString("yyyy-MM-dd hh:mm:ss.fff") + $" Length: {packet.Length}"); Console.WriteLine($"{ip.Source}:{tcp.SourcePort} -> {ip.Destination}:{tcp.DestinationPort}"); Console.WriteLine($"Sequence Number: {tcp.SequenceNumber}"); Console.WriteLine($"Payload Length: {tcp.PayloadLength}"); var payload = tcp.Decode(System.Text.Encoding.UTF8); Console.WriteLine($"Payload: {payload}"); if (tcp.IsAcknowledgment && !tcp.IsSynchronize && !tcp.IsFin) { payloads.Add(tcp); } else if (tcp.IsFin) { Console.WriteLine("#### Response:"); string response = String.Join("", payloads.Select(_tcp => { var _payload = _tcp.Decode(System.Text.Encoding.UTF8); if (_payload.Length != 0 && _payload.Length > 18) { _payload = _payload.Substring(18, _payload.Length - 18); } return(_payload); })); //striping Http Header var startOfHttpBody = response.IndexOf("\r\n\r\n"); if (startOfHttpBody == -1) { Console.WriteLine("No Http Response"); return; } Console.WriteLine($"idx:{startOfHttpBody}, len:{response.Length}"); response = response.Substring(startOfHttpBody, response.Length - startOfHttpBody); Console.WriteLine(response); File.WriteAllText("response.html", response); } } payloads = payloads.OrderBy(_tcp => _tcp.SequenceNumber).ToList(); }
// Callback function invoked by libpcap for every incoming packet private static void PacketHandler(Packet packet) { IpV4Datagram ip = packet.Ethernet.IpV4; TcpDatagram tcp = ip.Tcp; // print srcport and tcp payload in json format if (tcp.PayloadLength > 0) { WriteStdout(new SnifferMsg(tcp.SourcePort.ToString(), tcp.Payload.ToHexadecimalString())); } }
private PortInfo ParsePortInfo(Packet responce) { TcpDatagram datagram = responce.Ethernet.IpV4.Tcp; TcpControlBits bits = responce.Ethernet.IpV4.Tcp.ControlBits; bool isSynAck = bits.HasFlag(TcpControlBits.Acknowledgment) && bits.HasFlag(TcpControlBits.Synchronize); PortInfo info = new PortInfo(datagram.SourcePort, isSynAck); return(info); }
public void ProcessTCP(IpV4Datagram packet) { IpV4Datagram ip = packet; TcpDatagram tcp = packet.Tcp; uint TcpSessionHashCode = UtilityLib.GetTcpSessionHashCode(ip.CurrentDestination, tcp.DestinationPort, ip.Source, tcp.SourcePort); ITcpSession session = (ITcpSession)_tcp_sessions[TcpSessionHashCode]; if (session != null) { session.ProcessTCP(packet); } }
/// <summary> /// Parse an IP packet /// Dispatch TCP and UDP packets /// </summary> /// <param name="ip">The IP packet to be parsed</param> /// <param name="ctrl"></param> public static void ParseIPPacket(IpV4Datagram ip, object[] ctrl) { if (ip == null || ctrl == null || ctrl[0] == null || ctrl[1] == null) { return; } List <ListViewItem> items = new List <ListViewItem>(); ListViewItem item = new ListViewItem("IPV4"); string estr = "Destination = " + ip.Destination; estr += ", Source = " + ip.Source; estr += ", Next Protocol = " + ip.Protocol; estr += ", Packet ID = " + ip.Identification; estr += ", Total IP length = " + ip.Length; item.SubItems.Add(estr); items.Add(item); ListView f_details = (ListView)ctrl[0]; object[] param = new object[2]; param[0] = f_details; param[1] = items; f_details.BeginInvoke(new ParserHelper.UIHandler(ParserHelper.UpdateDetailsUI), param); switch (ip.Protocol) { case IpV4Protocol.Tcp: { TcpDatagram tcp = ip.Tcp; SnifferMain.datagram = tcp; SnifferMain.payload = tcp.Payload; ParseTcpPacket(tcp, ctrl[0]); PacketParser.DumpPacket(tcp, ctrl[1]); break; } case IpV4Protocol.Udp: { UdpDatagram udp = ip.Udp; SnifferMain.datagram = udp; SnifferMain.payload = udp.Payload; ParseUdpPacket(udp, ctrl[0]); PacketParser.DumpPacket(udp, ctrl[1]); break; } default: break; } }
public static void PrintPacket1(PPacket ppacket, bool detail = false, ITrace trace = null) { if (trace == null) { trace = Trace.CurrentTrace; } //************* 0 3 0.465083 192.168.0.1 52581 173.194.66.94 443 TCP ACK 0x0001 0x4B2091F9 0x4B2091FA 0x4695DD86 0x401A . //_tr.WriteLine("group no time source port destination port protocal flags length sequence next seq ack number window urgent"); StringBuilder sb = new StringBuilder(); //_tr.Write("{0,5} {1,5} {2,10:0.000000}", ppacket.GroupNumber, ppacket.PacketNumber, ppacket.RelativeTime.TotalSeconds); sb.AppendFormat("{0,5} {1,5} {2,10:0.000000}", ppacket.GroupNumber, ppacket.PacketNumber, ppacket.RelativeTime.TotalSeconds); sb.AppendFormat(" {0,-15} {1,5} {2,-15} {3,5} {4,-10}", ppacket.Source, ppacket.SourcePort, ppacket.Destination, ppacket.DestinationPort, ppacket.IpProtocolCode); if (detail) { TcpDatagram tcp = ppacket.Tcp; if (tcp != null && ppacket.Ipv4.Protocol == IpV4Protocol.Tcp) { sb.AppendFormat(" {0,-20}", ppacket.GetTcpFlagsString()); sb.AppendFormat(" {0,6}", tcp.PayloadLength > 0 ? "0x" + ((short)tcp.PayloadLength).zToHex() : null); sb.AppendFormat(" 0x{0} {1,10} {2,10} {3,6} {4,6}", ppacket.Tcp.SequenceNumber.zToHex(), tcp.NextSequenceNumber != tcp.SequenceNumber ? "0x" + tcp.NextSequenceNumber.zToHex() : null, tcp.AcknowledgmentNumber != 0 ? "0x" + tcp.AcknowledgmentNumber.zToHex() : null, "0x" + tcp.Window.zToHex(), tcp.UrgentPointer != 0 ? "0x" + tcp.UrgentPointer.zToHex() : null); int i = 0; int maxDataChar = 50; foreach (byte b in tcp.Payload) { if (++i > maxDataChar) { break; } if (b >= 32 && b <= 126) { sb.Append(((char)b).ToString()); } else { sb.Append("."); } } } else if (ppacket.Packet.Ethernet == null) { sb.Append(" not ethernet"); } } trace.WriteLine(sb.ToString()); }
public static void TestDecoratorDesign() { AppDatagram appDatagram = new AppDatagram(); appDatagram.SendData(); TcpDatagram tcpDatagram = new TcpDatagram(appDatagram); tcpDatagram.SendData(); UdpDatagram udpDatagram = new UdpDatagram(appDatagram); udpDatagram.SendData(); }
//[DataMember] //public int http_header_bytes { get; set; } public CustomPacket(Packet packet) { IpV4Datagram ip = packet.Ethernet.IpV4; UdpDatagram udp = ip.Udp; TcpDatagram tcp = ip.Tcp; ip_lenght = ip.Length; ip_header_lenght = ip.RealHeaderLength; ip_total_lenght = ip.TotalLength; ip_ttl = ip.Ttl; ip_service_type = ip.TypeOfService; ip_header_version = ip.Version; udp_check_sum = udp.Checksum; udp_dst_port = udp.DestinationPort; udp_cs_is_optional = udp.IsChecksumOptional; udp_is_valid = udp.IsValid; udp_scr_port = udp.SourcePort; udp_total_length = udp.TotalLength; tcp_check_sum = tcp.Checksum; tcp_dst_port = tcp.DestinationPort; tcp_header_lenght = tcp.HeaderLength; tcp_is_ack = tcp.IsAcknowledgment; tcp_cs_is_optional = tcp.IsChecksumOptional; tcp_is_cw_reduced = tcp.IsCongestionWindowReduced; tcp_is_ecne = tcp.IsExplicitCongestionNotificationEcho; tcp_is_nonce_sum = tcp.IsNonceSum; tcp_is_fin = tcp.IsFin; tcp_is_push = tcp.IsPush; tcp_is_reset = tcp.IsReset; tcp_is_syn = tcp.IsSynchronize; tcp_is_urgent = tcp.IsUrgent; tcp_is_valid = tcp.IsValid; tcp_lenght = tcp.Length; tcp_upointer = tcp.UrgentPointer; tcp_window = tcp.Window; if (tcp.Http != null) { http_is_request = tcp.Http.IsRequest; http_is_response = tcp.Http.IsResponse; } else { http_is_request = false; http_is_response = false; } }
/// <summary> /// Receives packet's datagram /// </summary> /// <returns>Tcp or Udp</returns> public static TransportDatagram GetDatagram(this Packet packet) { IpV4Datagram ip = packet.Ethernet.IpV4; if (ip.Protocol == IpV4Protocol.Tcp) { TcpDatagram tcp = ip.Tcp; return(tcp); } else { UdpDatagram udp = ip.Udp; return(udp); } }
/// <summary> /// Callback function invoked by libpcap for every incoming packet /// </summary> /// <param name="packet">captured packet</param> private void PacketHandler(Packet packet) { if (token.IsCancellationRequested) { Debug.WriteLine("PackHandle CANCELED"); return; } int hash = packet.GetSDHash(); IpV4Address src, dst; ushort srcPort, dstPort; packet.GetSrcDst(out src, out dst, out srcPort, out dstPort); if (CloseWaitConnections.ContainsKey(hash)) { CloseWaitConnections[hash].AddPacket(packet); } else if (ActiveConnections.ContainsKey(hash)) { ActiveConnections[hash].AddPacket(packet); } else if (EstWaitConnections.ContainsKey(hash)) { EstWaitConnections[hash].AddPacket(packet); } else { TcpDatagram tcp = packet.GetDatagram() as TcpDatagram; if (tcp != null) { if (tcp.IsSynchronize) { EstWaitConnections.Add(hash, new Connection(src, srcPort, dst, dstPort, packet, ConnectionClosedHandler, EstablishedHandler, CloseWaitHandler)); } } else { ActiveConnections.Add(hash, new Connection(src, srcPort, dst, dstPort, packet, ConnectionClosedHandler, EstablishedHandler, CloseWaitHandler)); } } }
// Callback function invoked by Pcap.Net for ps4 tcp messages private void PacketHandlerTcp(Packet packet) { IpV4Datagram ip = packet.Ethernet.IpV4; IpV4Protocol protocol = ip.Protocol; if (protocol == IpV4Protocol.Tcp) { TcpDatagram tcpDatagram = ip.Tcp; HttpDatagram httpDatagram = tcpDatagram.Http; if (httpDatagram.Length > 0 && httpDatagram.Header != null) { string httpPacket = httpDatagram.Decode(Encoding.UTF8); if (httpPacket.StartsWith("GET /sce/rp/session HTTP/1.1\r\n")) { Dictionary <string, string> header = HttpUtils.SplitHttpResponse(httpPacket); header.TryGetValue("RP-Registkey", out var registKey); this.textBoxPcapLogOutput.Invoke(new MethodInvoker(() => AppendLogOutputToPcapLogTextBox("RP-Registkey: " + registKey))); _livePcapContext.LivePcapState = LivePcapState.SESSION_REQUEST; _livePcapContext.Session = null; } else if (httpDatagram.IsResponse && httpPacket.StartsWith("HTTP/1.1 200 OK\r\n") && _livePcapContext.LivePcapState == LivePcapState.SESSION_REQUEST) { Dictionary <string, string> header = HttpUtils.SplitHttpResponse(httpPacket); header.TryGetValue("RP-Nonce", out var rpNonce); if (rpNonce == null) { return; } byte[] rpKeyBuffer = HexUtil.Unhexlify(_settingManager.GetRemotePlayData().RemotePlay.RpKey); byte[] rpNonceDecoded = Convert.FromBase64String(rpNonce); this.textBoxPcapLogOutput.Invoke(new MethodInvoker(() => AppendLogOutputToPcapLogTextBox("RP-Nonce from \"/sce/rp/session\" response: " + HexUtil.Hexlify(rpNonceDecoded)))); string controlAesKey = HexUtil.Hexlify(CryptoService.GetSessionAesKeyForControl(rpKeyBuffer, rpNonceDecoded)); string controlNonce = HexUtil.Hexlify(CryptoService.GetSessionNonceValueForControl(rpNonceDecoded)); this.textBoxPcapLogOutput.Invoke(new MethodInvoker(() => AppendLogOutputToPcapLogTextBox("!!! Control AES Key: " + controlAesKey))); this.textBoxPcapLogOutput.Invoke(new MethodInvoker(() => AppendLogOutputToPcapLogTextBox("!!! Control AES Nonce: " + controlNonce + Environment.NewLine))); _livePcapContext.LivePcapState = LivePcapState.SESSION_RESPONSE; _livePcapContext.Session = CryptoService.GetSessionForControl(rpKeyBuffer, rpNonceDecoded); } } } }
public void ReassemblePacket(Packet packet) { TcpDatagram tcp = packet.Ethernet.IpV4.Tcp; // if the paylod length is zero bail out //ulong length = (ulong)(tcpPacket.TCPPacketByteLength - tcpPacket.TCPHeaderLength); int length = tcp.PayloadLength; if (length == 0) { return; } //reassemble_tcp((ulong)tcpPacket.SequenceNumber, length, tcpPacket.TCPData, (ulong)tcpPacket.TCPData.Length, tcpPacket.Syn, // tcpPacket.SourceAddressAsLong, tcpPacket.DestinationAddressAsLong, (uint)tcpPacket.SourcePort, (uint)tcpPacket.DestinationPort); reassemble_tcp(tcp.SequenceNumber, (uint)length, tcp.Payload.ToArray(), (uint)tcp.PayloadLength, tcp.IsSynchronize, packet.Ethernet.IpV4.Source.ToValue(), tcp.SourcePort, packet.Ethernet.IpV4.Destination.ToValue(), tcp.DestinationPort); }
public string GetErrorMessage(TcpPacketError error) { //TCP tcp = Packet.TCP; TcpDatagram tcp = _packet.Ethernet.IpV4.Tcp; switch (error) { case TcpPacketError.ErrorBadDirection: return("error wrong direction"); case TcpPacketError.WarningBadFlagAck: return("warning ack should not be set"); case TcpPacketError.WarningOpenConnection2BadAck: return(string.Format("warning ack (0x{0}) != source seq + 1 (0x{1})", tcp.AcknowledgmentNumber.zToHex(), (StreamState.CurrentSourceSequence - 1).zToHex())); case TcpPacketError.WarningOpenConnection2BadMessagePosition: return("warning message should be just after open connection step 1"); case TcpPacketError.ErrorOpenConnection2BadDirection: return(string.Format("error wrong direction, TCP open 2, SYN seq = y (0x{0}), ACK x + 1 (0x{1})", tcp.SequenceNumber.zToHex(), tcp.AcknowledgmentNumber.zToHex())); case TcpPacketError.WarningOpenConnection3BadAck: return(string.Format("warning ack (0x{0}) != destination seq + 1 (0x{1})", tcp.AcknowledgmentNumber.zToHex(), StreamState.CurrentDestinationSequence.zToHex())); case TcpPacketError.WarningCloseSourceConnection1BadSeq: return(string.Format("warning seq (0x{0}) != source seq (0x{1})", tcp.SequenceNumber.zToHex(), StreamState.CurrentSourceSequence.zToHex())); case TcpPacketError.WarningCloseSourceConnection2BadAck: return(string.Format("warning ack (0x{0}) != source seq + 1 (0x{1})", tcp.AcknowledgmentNumber.zToHex(), StreamState.CurrentSourceSequence.zToHex())); case TcpPacketError.WarningCloseDestinationConnection1BadSeq: return(string.Format("warning seq (0x{0}) != destination seq (0x{1})", tcp.SequenceNumber.zToHex(), StreamState.CurrentDestinationSequence.zToHex())); case TcpPacketError.WarningCloseDestinationConnection1BadAck: return(string.Format("warning ack (0x{0}) != source seq + 1 (0x{1})", tcp.AcknowledgmentNumber.zToHex(), StreamState.CurrentSourceSequence.zToHex())); case TcpPacketError.WarningCloseDestinationConnection2BadAck: return(string.Format("warning ack (0x{0}) != destination seq + 1 (0x{1}) (ACK y + 1)", tcp.AcknowledgmentNumber.zToHex(), StreamState.CurrentDestinationSequence.zToHex())); default: return(null); } }
//private static void PrintIpAdressList(Packet packet) private static void PrintIpAdressList(PPacket ppacket) { Packet packet = ppacket.Packet; //if (packet.Ethernet == null) // return; //IpV4Datagram ip = packet.Ethernet.IpV4; IpV4Datagram ip = ppacket.Ipv4; if (ip == null) { return; } uint ipAdress = ip.Source.ToValue(); if (!_ipAdressList.ContainsKey(ipAdress)) { _ipAdressList.Add(ipAdress, null); Trace.WriteLine("new ip adress {0}", ip.Source.ToString()); } ipAdress = ip.Destination.ToValue(); if (!_ipAdressList.ContainsKey(ipAdress)) { _ipAdressList.Add(ipAdress, null); Trace.WriteLine("new ip adress {0}", ip.Destination.ToString()); } //TcpDatagram tcp = ip.Tcp; TcpDatagram tcp = ppacket.Tcp; if (tcp == null) { return; } TcpConnection tcpConnection = new TcpConnection(packet); if (!_tcpStreamList.ContainsKey(tcpConnection)) { _tcpStreamList.Add(tcpConnection, null); //_tr.WriteLine("new tcp stream {0}:{1} {2}:{3}", tcpConnection.Source.IpAddress, tcpConnection.Source.Port, // tcpConnection.Destination.IpAddress, tcpConnection.Destination.Port); Trace.WriteLine("new tcp stream {0}", tcpConnection.GetConnectionName()); } }
public Connection(IpV4Address source, ushort sourcePort, IpV4Address destination, ushort destinationPort, Packet packet, EventHandler timerHandler, EventHandler establishedHandler, EventHandler closeWaitHandler) { this.source = source; this.sourcePort = sourcePort; this.destination = destination; this.destinationPort = destinationPort; startTime = DateTime.MinValue; endTime = startTime; connectionClosedEvent += timerHandler; connectionEstablishedEvent += establishedHandler; connectionCloseAttempEvent += closeWaitHandler; timer = new Timer(CallEventHandler, connectionClosedEvent, timeWait, -1); packets = new List <Packet>(); directPackets = new List <Packet>(); backPackets = new List <Packet>(); packets.Add(packet); IpV4Datagram ip = packet.Ethernet.IpV4; protocol = ip.Protocol; TcpDatagram tcp = packet.GetDatagram() as TcpDatagram; isTcp = packet.GetDatagram() is TcpDatagram; if (tcp != null) { ++synCount; directPackets.Add(packet); } else { directPackets.Add(packet); isEstablished = true; } }
private void PrintTcp(PPacket ppacket) { //IpV4Datagram ip = ppacket.Packet.Ethernet.IpV4; TcpDatagram tcp = ppacket.Packet.Ethernet.IpV4.Tcp; //if (ip.Protocol != IpV4Protocol.Tcp) // return; _dataLength -= (ushort)tcp.RealHeaderLength; WriteTitle("[tcp frame]"); WriteValues(2, "source port", tcp.SourcePort, "header length", tcp.RealHeaderLength); //WriteValues(2, "destination port", tcp.DestinationPort, "data length", _dataLength); WriteValues(2, "destination port", tcp.DestinationPort); WriteValues(4, "sequence number", "0x" + tcp.SequenceNumber.zToHex()); WriteValues(4, "acknowledgment number", "0x" + tcp.AcknowledgmentNumber.zToHex()); WriteValues(2, "data offset", "0x" + ((byte)tcp.HeaderLength).zToHex()); WriteValues(0, "ecn", tcp.IsExplicitCongestionNotificationEcho); WriteValues(0, "cwr", tcp.IsCongestionWindowReduced); WriteValues(0, "ece", tcp.IsExplicitCongestionNotificationEcho); WriteValues(0, "urg", tcp.IsUrgent); WriteValues(0, "ack", tcp.IsAcknowledgment); WriteValues(0, "psh", tcp.IsPush); WriteValues(0, "rst", tcp.IsReset); WriteValues(0, "syn", tcp.IsSynchronize); WriteValues(0, "fin", tcp.IsFin); WriteValues(2, "window size", "0x" + tcp.Window.zToHex()); WriteValues(2, "checksum", "0x" + tcp.Checksum.zToHex()); WriteValues(2, "urgent pointer", "0x" + tcp.UrgentPointer.zToHex()); int optionLength = tcp.RealHeaderLength - 20; int n = Math.Min(8, optionLength); WriteValues(n, "options", null, "options length", optionLength); optionLength -= n; while (optionLength > 0) { n = Math.Min(8, optionLength); WriteValues(n); optionLength -= n; } WriteTitle("[tcp data]"); WritePayloadData(48, tcp.Payload.zAsEnumerableWithCounter(_dataEnum.Index)); }
void AddPacket(TcpDatagram tcp, bool inc, PacketInfo.Daemon daemon, ushort port) { foreach (var p in packets) { if (p.Tcp.SequenceNumber == tcp.SequenceNumber) { #if DEBUG Console.WriteLine("Dropping duplicate packet..."); #endif return; } } packets.Enqueue(new PacketClass(tcp, inc, daemon, port)); if (packets.Count > 10) { var p = packets.Dequeue(); var data = p.Tcp.Payload.ToMemoryStream(); ProcessPacket(data.ToArray(), p.IsIncoming, p.Daemon, p.Port); } }
bool IsWorld(TcpDatagram tcp, bool inc) { for (int i = 0; i < Ports.I.WorldPortsStart.Count; i++) { if (inc) { if (tcp.SourcePort >= Ports.I.WorldPortsStart[i] && tcp.SourcePort <= Ports.I.WorldPortsEnd[i]) { return(true); } } else { if (tcp.DestinationPort >= Ports.I.WorldPortsStart[i] && tcp.DestinationPort <= Ports.I.WorldPortsEnd[i]) { return(true); } } } return(false); }
private static string GetConnString(PcapDotNet.Packets.Packet packet) { String srcIp = ""; String dstIp = ""; TcpDatagram tcp = null; EthernetDatagram eth = packet.Ethernet; switch (eth.EtherType) { case EthernetType.IpV4: IpV4Datagram ip = eth.IpV4; tcp = ip.Tcp; srcIp = ip.Source.ToString(); dstIp = ip.Destination.ToString(); break; case EthernetType.IpV6: IpV6Datagram ip6 = eth.IpV6; tcp = ip6.Tcp; srcIp = ip6.Source.ToString(); dstIp = ip6.CurrentDestination.ToString(); break; default: Console.WriteLine("We should never see anything not ipv4 or ipv6 since we filtered by tcp"); return(""); } StringBuilder sb = new StringBuilder(); sb.Append(srcIp); sb.Append(":"); sb.Append(tcp.SourcePort); sb.Append(" to "); sb.Append(dstIp); sb.Append(":"); sb.Append(tcp.DestinationPort); return(sb.ToString()); }