public void ReadXml(System.Xml.XmlReader reader) { while (!reader.IsStartElement("Blockedip")) { reader.Read(); } reader.ReadStartElement("Blockedip"); XmlSerializer ipSerialization = new XmlSerializer(typeof(IPAddr)); Blockedip = (IPAddr)ipSerialization.Deserialize(reader); reader.ReadEndElement(); while (!reader.IsStartElement("DateBlocked")) { reader.Read(); } reader.ReadStartElement("DateBlocked"); DateBlocked = (long)new XmlSerializer(typeof(long)).Deserialize(reader); reader.ReadEndElement(); while (!reader.IsStartElement("Reason")) { reader.Read(); } reader.ReadStartElement("Reason"); Reason = (string)new XmlSerializer(typeof(string)).Deserialize(reader); reader.ReadEndElement(); reader.ReadEndElement(); }
public void Add(IPAddr ip) { try { locker.AcquireWriterLock(new TimeSpan(0, 1, 0)); try { if (list.ContainsKey(ip)) { list[ip] = DateTime.UtcNow.Ticks; } else { list.Add(ip, DateTime.UtcNow.Ticks); } } finally { locker.ReleaseWriterLock(); } } catch (ApplicationException e) { Logging.LogCenter.Instance.LogException(e); } }
/// <summary> /// Generates a report on the selected IP address; pretty much just formats everything found /// in its IPObj object /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void infoButton_Click(object sender, EventArgs e) { int rowIdx = 0; string ip = null; fireBwall.Utils.IPObj tmp; if (blockedIPList.SelectedRows.Count <= 0) { ip = potentialIPBox.SelectedItem.ToString(); tmp = detector.potentials[IPAddr.Parse(ip)]; } else if (potentialIPBox.SelectedIndex < 0) { rowIdx = blockedIPList.SelectedCells[0].RowIndex; ip = blockedIPList["IP", rowIdx].Value.ToString(); tmp = detector.data.BlockCache[IPAddr.Parse(ip)]; } else { return; } // go generate the report Report report = new Report(); report.GenerateReport(tmp); }
public bool Contains(IPAddr ip, long secondsOld = -1) { bool contains = false; try { locker.AcquireReaderLock(new TimeSpan(0, 1, 0)); try { if (secondsOld < 0) { contains = list.ContainsKey(ip); } else { contains = (list.ContainsKey(ip) && new DateTime(list[ip]).AddSeconds(secondsOld).CompareTo(DateTime.UtcNow) < 0); } } finally { locker.ReleaseReaderLock(); } } catch (ApplicationException a) { Logging.LogCenter.Instance.LogException(a); } return(contains); }
public bool InList(string list, IPAddr ip, long secondsOld = -1) { bool ret = false; try { locker.AcquireReaderLock(new TimeSpan(0, 1, 0)); try { IPList ipl; if (iplists.TryGetValue(list, out ipl)) { if (ipl.Contains(ip, secondsOld)) { ret = true; } } } finally { locker.ReleaseReaderLock(); } } catch (ApplicationException ex) { Logging.LogCenter.Instance.LogException(ex); } return(ret); }
public bool Contains(IPAddr ip, long secondsOld = -1) { bool contains = false; try { locker.AcquireReaderLock(new TimeSpan(0, 1, 0)); try { if (secondsOld < 0) { contains = list.ContainsKey(ip); } else { contains = (list.ContainsKey(ip) && new DateTime(list[ip]).AddSeconds(secondsOld).CompareTo(DateTime.UtcNow) < 0); } } finally { locker.ReleaseReaderLock(); } } catch (ApplicationException a) { Logging.LogCenter.Instance.LogException(a); } return contains; }
public ConnectVM() { Ip = new IPAddr(); Ip.Ip = "192.168.1.102"; Ip.Port = "31313"; BtnConnectCmd = new RelayCommand(new Action <object>(Connect)); IsEnable = true; }
public void IPAddrSerialization() { XmlSerializer serializer = new XmlSerializer(typeof(IPAddr)); MemoryStream ms = new MemoryStream(); IPAddr outAddr = IPAddr.Parse("192.168.1.1"); serializer.Serialize(ms, outAddr); ms.Position = 0; IPAddr inAddr = (IPAddr)serializer.Deserialize(ms); Assert.AreEqual("192.168.1.1", inAddr.ToString()); }
/// <summary> /// removes the blocked IP address from the table and the block cache /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void removeBlockedButton_Click(object sender, EventArgs e) { if (blockedIPList.SelectedRows.Count < 0) { return; } int rowIdx = blockedIPList.SelectedCells[0].RowIndex; string ip = blockedIPList["IP", rowIdx].Value.ToString(); // remove it from the block cache detector.data.BlockCache.Remove(IPAddr.Parse(ip)); blockedIPList.Rows.RemoveAt(rowIdx); }
/// <summary> /// Adds a potential IP address /// </summary> /// <param name="addr"></param> public void addPotential(IPAddr addr) { if (potentialIPBox.InvokeRequired) { potentialIPBox.Invoke((MethodInvoker)delegate { addPotential(addr); }); } else { if (!potentialIPBox.Items.Contains(addr.ToString())) this.potentialIPBox.Items.Add(addr.ToString()); } }
private void button1_Click_1(object sender, EventArgs e) { try { if (listBox1.SelectedItem != null) { string i = (string)listBox1.SelectedItem; IPAddr ip = IPAddr.Parse(i.Split(' ')[2]); cache.Remove(ip); saap.UpdateCache(cache); cache = saap.GetCache(); saap_UpdatedArpCache(); } } catch { } }
public void scanAll() { if (startIP != null && endIP != null) { IPAddr ipAddr = new IPAddr(startIP); while (endIP.larger(ipAddr)) { scanUser(ipAddr); ipAddr.increase(); if (isStopScan) { break; } } } }
/// <summary> /// Handles the IP add button /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void addButton_Click(object sender, EventArgs e) { // if the given string is a valid IPv4 addr. // IPAddress.TryParse is broken. if (regIP.IsMatch(addField.Text)) { IPAddr t = IPAddr.Parse(addField.Text); blockcache.Add(new BlockedIP(t, DateTime.UtcNow, "User added")); // update the module blockcache and update the table UpdateBlockedCache(); RebuildTable(); // consume input addField.Text = ""; } }
/// <summary> /// handles the block button action; adds the selected IP address /// to the block list /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void blockButton_Click(object sender, EventArgs e) { if (potentialIPBox.SelectedIndex < 0) { return; } String ip = potentialIPBox.SelectedItem.ToString(); // add it to the data block cache detector.data.BlockCache.Add(IPAddr.Parse(ip), detector.potentials[IPAddr.Parse(ip)]); // remove it from the potential list potentialIPBox.Items.Remove(ip); detector.potentials.Remove(IPAddr.Parse(ip)); // add it to the block list blockedIPList.Rows.Add(ip); }
public void Connect(object obj) { IPAddr ipTemp = obj as IPAddr; App.NetCtrl = new NetCtrl(ipTemp.Ip, ipTemp.Port); App.NetCtrl.Send("1|1|"); if (App.NetCtrl.SocketClient.Connected) { LoginV loginV = new LoginV(); loginV.Show(); IsEnable = false; } else { MessageBox.Show("连接失败"); } }
/// <summary> /// Adds a potential IP address /// </summary> /// <param name="addr"></param> public void addPotential(IPAddr addr) { if (potentialIPBox.InvokeRequired) { potentialIPBox.Invoke((MethodInvoker) delegate { addPotential(addr); }); } else { if (!potentialIPBox.Items.Contains(addr.ToString())) { this.potentialIPBox.Items.Add(addr.ToString()); } } }
public void ListofIPAddrSerialization() { XmlSerializer serializer = new XmlSerializer(typeof(List <IPAddr>)); MemoryStream ms = new MemoryStream(); IPAddr outAddr = IPAddr.Parse("192.168.1.1"); List <IPAddr> list = new List <IPAddr>(); list.Add(outAddr); list.Add(outAddr); list.Add(outAddr); serializer.Serialize(ms, list); ms.Position = 0; List <IPAddr> inAddr = (List <IPAddr>)serializer.Deserialize(ms); Assert.AreEqual("192.168.1.1", inAddr[0].ToString()); Assert.AreEqual("192.168.1.1", inAddr[1].ToString()); Assert.AreEqual("192.168.1.1", inAddr[2].ToString()); }
public void DictionaryofIPAddrSerialization() { XmlSerializer serializer = new XmlSerializer(typeof(SerializableDictionary <IPAddr, IPAddr>)); MemoryStream ms = new MemoryStream(); IPAddr outAddr = IPAddr.Parse("192.168.1.1"); SerializableDictionary <IPAddr, IPAddr> list = new SerializableDictionary <IPAddr, IPAddr>(); list.Add(outAddr, outAddr); serializer.Serialize(ms, list); ms.Position = 0; SerializableDictionary <IPAddr, IPAddr> inAddr = (SerializableDictionary <IPAddr, IPAddr>)serializer.Deserialize(ms); foreach (KeyValuePair <IPAddr, IPAddr> pair in inAddr) { Assert.AreEqual("192.168.1.1", pair.Key.ToString()); Assert.AreEqual("192.168.1.1", pair.Value.ToString()); } }
public void SerializableDictionaryOfIPAddrSerialization() { XmlSerializer serializer = new XmlSerializer(typeof(SerializableList <IPAddr>)); MemoryStream ms = new MemoryStream(); IPAddr outAddr = IPAddr.Parse("192.168.1.1"); SerializableList <IPAddr> list = new SerializableList <IPAddr>(); list.Add(outAddr); list.Add(outAddr); serializer.Serialize(ms, list); ms.Position = 0; SerializableList <IPAddr> inAddr = (SerializableList <IPAddr>)serializer.Deserialize(ms); foreach (IPAddr ip in inAddr) { Assert.AreEqual("192.168.1.1", ip.ToString()); Assert.AreEqual("192.168.1.1", ip.ToString()); } }
public void AddToList(string list, IPAddr ip) { try { LockCookie upgrade = new LockCookie(); bool upgraded = false; if (locker.IsReaderLockHeld) { upgrade = locker.UpgradeToWriterLock(new TimeSpan(0, 1, 0)); upgraded = true; } else { locker.AcquireWriterLock(new TimeSpan(0, 1, 0)); } try { if (!iplists.ContainsKey(list)) { iplists[list] = new IPList(); } iplists[list].Add(ip); } finally { if (upgraded) { locker.DowngradeFromWriterLock(ref upgrade); } else { locker.ReleaseWriterLock(); } } } catch (ApplicationException a) { Logging.LogCenter.Instance.LogException(a); } }
public static IPAddr GetLocalIPAddress(INDISFilter adapter) { IPAddr address = new IPAddr(); NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces(); foreach (var adapt in nics) { // if this adapter matches the one we're looking for if (adapt.Id.Equals(adapter.GetAdapterInformation().Id)) { foreach(var i in adapt.GetIPProperties().UnicastAddresses) { if (i.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) { address = new IPAddr(i.Address.GetAddressBytes()); return address; } } } } return null; }
/// <summary> /// Check if an IP address falls within the given range /// </summary> /// <param name="addr">address to check</param> /// <returns>true/false</returns> public bool IsInRange(IPAddr addr) { byte[] addrBytes = addr.GetAddressBytes(); bool lBound = true; bool uBound = true; // iterate over ip bytes in the range for (int i = 0; i < this.lowerBytes.Length && (lBound || uBound); ++i) { if ((lBound && addrBytes[i] < lowerBytes[i]) || (uBound && addrBytes[i] > upperBytes[i])) { return(false); } lBound &= (addrBytes[i] == lowerBytes[i]); uBound &= (addrBytes[i] == upperBytes[i]); } return(true); }
public void Remove(IPAddr ip) { try { locker.AcquireReaderLock(new TimeSpan(0, 1, 0)); try { if (list.ContainsKey(ip)) { LockCookie lc = new LockCookie(); try { lc = locker.UpgradeToWriterLock(new TimeSpan(0, 1, 0)); try { list.Remove(ip); } finally { locker.DowngradeFromWriterLock(ref lc); } } catch (ApplicationException e) { Logging.LogCenter.Instance.LogException(e); } } } finally { locker.ReleaseReaderLock(); } } catch (ApplicationException aex) { Logging.LogCenter.Instance.LogException(aex); } }
public void Add(IPAddr ip) { try { locker.AcquireWriterLock(new TimeSpan(0, 1, 0)); try { if (list.ContainsKey(ip)) list[ip] = DateTime.UtcNow.Ticks; else list.Add(ip, DateTime.UtcNow.Ticks); } finally { locker.ReleaseWriterLock(); } } catch (ApplicationException e) { Logging.LogCenter.Instance.LogException(e); } }
public static bool TryParse(string ipAddr, out IPAddr addr) { addr = null; if (Regex.IsMatch(ipAddr, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$")) { int[] ip = new int[4]; int index = 0; for (int i = 0; i < ipAddr.Length; ++i) { if (ipAddr[i] == '.') { ++index; } else { ip[index] = ip[index] * 10 + ipAddr[i] - '0'; } } addr = new IPAddr(ip); return true; } return false; }
private void scanUser(IPAddr ipAddr) { string send = "SCAN" + listener.localInfo.Name + "\0" + listener.localInfo.Port; IPEndPoint ip = new IPEndPoint(IPAddress.Parse(ipAddr.ToString()), this.port); Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); byte[] bytes = Encoding.UTF8.GetBytes(send); server.SendTo(bytes, ip); bytes = new byte[1024]; IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0); EndPoint remote = (EndPoint)sender; server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 1000); try { int recv = server.ReceiveFrom(bytes, ref remote); if (recv >= 4) { UserInfo info = new UserInfo(); string[] strs = Encoding.UTF8.GetString(bytes, 0, recv).Substring(4).Split(new char[1] { '\0' }); info.Name = strs[0]; info.IP = ipAddr.ToString(); info.Port = this.port; lock (listener) { listener.addUser(info); } } } catch { } server.Close(); }
public bool larger(IPAddr addr) { for (int i = 0; i < 4; ++i) { if (this.ip[i] < addr.ip[i]) { return false; } } return true; }
public IPAddr(IPAddr ipAddr) { for (int i = 0; i < 4; ++i) { this.ip[i] = ipAddr.ip[i]; } }
/// <summary> /// Checks if an IP is local /// </summary> /// <param name="ip"></param> /// <returns></returns> private bool isLocalIP(IPAddr ip) { return(Adapter.GetAdapterInformation().IPv4.Equals(ip) || Adapter.GetAdapterInformation().IPv6.Equals(ip)); }
/// <summary> /// Check if an IP address falls within the given range /// </summary> /// <param name="addr">address to check</param> /// <returns>true/false</returns> public bool IsInRange(IPAddr addr) { byte[] addrBytes = addr.GetAddressBytes(); bool lBound = true; bool uBound = true; // iterate over ip bytes in the range for (int i = 0; i < this.lowerBytes.Length && (lBound || uBound); ++i) { if ((lBound && addrBytes[i] < lowerBytes[i]) || (uBound && addrBytes[i] > upperBytes[i])) { return false; } lBound &= (addrBytes[i] == lowerBytes[i]); uBound &= (addrBytes[i] == upperBytes[i]); } return true; }
//Helper get method for IPAddress type public string getStringIPAddress() { return(IPAddr.ToString()); }
// def init public BlockedIP() { this.Blockedip = new IPAddr(); DateBlocked = DateTime.UtcNow.Ticks; Reason = ""; }
public override PacketMainReturnType interiorMain(ref Packet in_packet) { if (in_packet.GetHighestLayer() == Protocol.ARP) { ARPPacket arpp = (ARPPacket)in_packet; if (arpp.isRequest && arpp.Outbound) { IPAddr ip = new IPAddr(arpp.ATargetIP.GetAddressBytes()); if (!requestedIPs.Contains(ip)) { requestedIPs.Add(ip); } } else if (!arpp.Outbound) { IPAddr ip = new IPAddr(arpp.ASenderIP.GetAddressBytes()); if (!arpp.isRequest) { if (requestedIPs.Contains(ip)) { lock (padlock) { if (data.arpCache.ContainsKey(new IPAddr(arpp.ASenderIP.GetAddressBytes()))) { if (!Utility.ByteArrayEq(data.arpCache[new IPAddr(arpp.ASenderIP.GetAddressBytes())].AddressBytes, arpp.ASenderMac)) { PacketMainReturnType pmr = 0; if (data.RectifyAttacks) { pmr = PacketMainReturnType.Edited; } else { pmr = PacketMainReturnType.Drop; } if (data.LogAttacks) { LogEvent le = new LogEvent(String.Format(multistring.GetString("Response does not equal cache"), new PhysicalAddress(arpp.ASenderMac).ToString(), arpp.ASenderIP.ToString()), this); le.PMR = PacketMainReturnType.Log | PacketMainReturnType.Popup; LogCenter.Instance.LogEvent(le); } if (data.RectifyAttacks) { arpp.ATargetIP = arpp.ASenderIP; arpp.ATargetMac = data.arpCache[new IPAddr(arpp.ATargetIP.GetAddressBytes())].AddressBytes; arpp.ASenderMac = this.Adapter.GetAdapterInformation().InterfaceInformation.GetPhysicalAddress().GetAddressBytes(); arpp.FromMac = arpp.ASenderMac; arpp.ToMac = arpp.ATargetMac; arpp.ASenderIP = Adapter.GetAdapterInformation().IPv4; arpp.Outbound = true; in_packet = arpp; } return(pmr); } else { requestedIPs.Remove(ip); } } else { data.arpCache[new IPAddr(arpp.ASenderIP.GetAddressBytes())] = new MACAddr(arpp.ASenderMac); if (UpdatedArpCache != null) { UpdatedArpCache(); } requestedIPs.Remove(ip); } } } else { lock (padlock) { if (data.arpCache.ContainsKey(new IPAddr(arpp.ASenderIP.GetAddressBytes()))) { if (!Utility.ByteArrayEq(data.arpCache[new IPAddr(arpp.ASenderIP.GetAddressBytes())].AddressBytes, arpp.ASenderMac)) { PacketMainReturnType pmra = 0; if (data.RectifyAttacks) { pmra = PacketMainReturnType.Edited; } else { pmra = PacketMainReturnType.Drop; } if (data.LogAttacks) { LogEvent le = new LogEvent(String.Format(multistring.GetString("Response does not equal cache"), new PhysicalAddress(arpp.ASenderMac).ToString(), arpp.ASenderIP.ToString()), this); le.PMR = PacketMainReturnType.Log | PacketMainReturnType.Popup; LogCenter.Instance.LogEvent(le); } if (data.RectifyAttacks) { arpp.ATargetIP = arpp.ASenderIP; arpp.ATargetMac = data.arpCache[new IPAddr(arpp.ATargetIP.GetAddressBytes())].AddressBytes; arpp.ASenderMac = this.Adapter.GetAdapterInformation().InterfaceInformation.GetPhysicalAddress().GetAddressBytes(); arpp.FromMac = arpp.ASenderMac; arpp.ToMac = arpp.ATargetMac; arpp.ASenderIP = Adapter.GetAdapterInformation().IPv4; arpp.Outbound = true; in_packet = arpp; } return(pmra); } } } PacketMainReturnType pmr = 0; pmr = PacketMainReturnType.Drop; if (data.LogUnsolic) { LogEvent le2 = new LogEvent(String.Format(multistring.GetString("Unsolicited"), new PhysicalAddress(arpp.ASenderMac).ToString(), arpp.ASenderIP.ToString()), this); le2.PMR = PacketMainReturnType.Log; } return(pmr); } } else { lock (padlock) { if (data.arpCache.ContainsKey(new IPAddr(arpp.ASenderIP.GetAddressBytes()))) { if (!Utility.ByteArrayEq(data.arpCache[new IPAddr(arpp.ASenderIP.GetAddressBytes())].AddressBytes, arpp.ASenderMac)) { PacketMainReturnType pmr = PacketMainReturnType.Drop; if (data.LogAttacks) { LogEvent le = new LogEvent(String.Format(multistring.GetString("Response does not equal cache"), new PhysicalAddress(arpp.ASenderMac).ToString(), arpp.ASenderIP.ToString()), this); le.PMR = PacketMainReturnType.Log | PacketMainReturnType.Popup; LogCenter.Instance.LogEvent(le); } return(pmr); } } } } return(0); } return(0); } return(0); }
/// <summary> /// Determine whether a given IP address is blocked /// /// Note to Drone: HashSet would make this faster, even more so after IPv6 is connected everywheres /// </summary> /// <param name="i">IP address to resolve</param> /// <returns>bool</returns> private bool isIPAllowed(IPAddr i) { return !data.BlockCache.ContainsKey(i); }
public IPObj(IPAddr addr) { this.Address = addr; time(DateTime.Now); }
static async Task FqdnScanAsync(ConsoleService c, string cmdName, string str) { ConsoleParam[] args = { new ConsoleParam("[subnets]", ConsoleService.Prompt, "Subnets: ", ConsoleService.EvalNotEmpty, null), new ConsoleParam("servers"), new ConsoleParam("threads"), new ConsoleParam("interval"), new ConsoleParam("try"), new ConsoleParam("shuffle"), new ConsoleParam("fqdnorder"), new ConsoleParam("dest"), new ConsoleParam("ports"), }; ConsoleParamValueList vl = c.ParseCommandList(cmdName, str, args); string subnets = vl.DefaultParam.StrValue; string servers = vl["servers"].StrValue; int threads = vl["threads"].IntValue; int interval = vl["interval"].IntValue; int numtry = vl["try"].IntValue; bool shuffle = vl["shuffle"].StrValue._ToBool(true); bool fqdnorder = vl["fqdnorder"].StrValue._ToBool(true); string csv = vl["dest"].StrValue; string portsStr = vl["ports"].StrValue; PortRange portRange = new PortRange(portsStr); var serversList = servers._Split(StringSplitOptions.RemoveEmptyEntries, " ", " ", ",", "|"); if (serversList._IsEmpty()) { serversList = new string[] { "8.8.8.8", "8.8.4.4", "1.1.1.1", "3.3.3.3" }; } List <IPEndPoint> endPointsList = new List <IPEndPoint>(); serversList._DoForEach(x => endPointsList.Add(new IPEndPoint(x._ToIPAddress() !, 53))); using DnsHostNameScanner scan = new DnsHostNameScanner( settings: new DnsHostNameScannerSettings { Interval = interval, NumThreads = threads, NumTry = numtry, PrintStat = true, RandomInterval = true, Shuffle = shuffle, PrintOrderByFqdn = fqdnorder, TcpPorts = portRange.ToArray(), }, dnsSettings: new DnsResolverSettings(dnsServersList: endPointsList, flags: DnsResolverFlags.UdpOnly | DnsResolverFlags.RoundRobinServers)); var list = await scan.PerformAsync(subnets); if (csv._IsFilled()) { using var csvWriter = Lfs.WriteCsv <FqdnScanResult>(csv, false, true, writeBom: false, flags: FileFlags.AutoCreateDirectory); foreach (var item in list) { if (item.HostnameList._IsFilled()) { FqdnScanResult r = new FqdnScanResult(); r.IpSortKey = IPAddr.FromAddress(item.Ip).GetZeroPaddingFullString(); r.Ip = item.Ip.ToString(); r.FqdnSortKey = Str.ReverseFqdnStr(item.HostnameList.First()).ToLowerInvariant(); r.FqdnList = item.HostnameList._Combine(" / "); r.TcpPortList = item.TcpPorts.Select(x => x.ToString())._Combine(" / "); csvWriter.WriteData(r); } } } }
public bool InList(string list, IPAddr ip, long secondsOld = -1) { bool ret = false; try { locker.AcquireReaderLock(new TimeSpan(0, 1, 0)); try { IPList ipl; if (iplists.TryGetValue(list, out ipl)) { if (ipl.Contains(ip, secondsOld)) ret = true; } } finally { locker.ReleaseReaderLock(); } } catch (ApplicationException ex) { Logging.LogCenter.Instance.LogException(ex); } return ret; }
// constructor with vars public BlockedIP(IPAddr b, DateTime d, string s) { this.Blockedip = b; this.DateBlocked = d.Ticks; this.Reason = s; }
public void AddToList(string list, IPAddr ip) { try { LockCookie upgrade = new LockCookie(); bool upgraded = false; if (locker.IsReaderLockHeld) { upgrade = locker.UpgradeToWriterLock(new TimeSpan(0, 1, 0)); upgraded = true; } else locker.AcquireWriterLock(new TimeSpan(0, 1, 0)); try { if (!iplists.ContainsKey(list)) { iplists[list] = new IPList(); } iplists[list].Add(ip); } finally { if (upgraded) locker.DowngradeFromWriterLock(ref upgrade); else locker.ReleaseWriterLock(); } } catch (ApplicationException a) { Logging.LogCenter.Instance.LogException(a); } }
public override PacketMainReturnType interiorMain(ref Packet in_packet) { PacketMainReturnType pmr; LogEvent le; float av = 0; if (in_packet.ContainsLayer(Protocol.TCP)) { // if we're in cloaked mode, respond with the SYN ACK // More information about this in the GUI code and help string if (data.cloaked_mode && ((TCPPacket)in_packet).SYN && !((TCPPacket)in_packet).ACK) { TCPPacket from = (TCPPacket)in_packet; EthPacket eth = new EthPacket(60); eth.FromMac = Adapter.GetAdapterInformation().InterfaceInformation.GetPhysicalAddress().GetAddressBytes(); eth.ToMac = from.FromMac; eth.Proto = new byte[2] { 0x08, 0x00 }; IPPacket ip = new IPPacket(eth); ip.DestIP = from.SourceIP; ip.SourceIP = from.DestIP; ip.NextProtocol = 0x06; ip.TotalLength = 40; ip.HeaderChecksum = ip.GenerateIPChecksum; TCPPacket tcp = new TCPPacket(ip); tcp.SourcePort = from.DestPort; tcp.DestPort = from.SourcePort; tcp.SequenceNumber = (uint)new Random().Next(); tcp.AckNumber = 0; tcp.WindowSize = 8192; tcp.SYN = true; tcp.ACK = true; tcp.Checksum = tcp.GenerateChecksum; tcp.Outbound = true; Adapter.SendPacket(tcp); } try { TCPPacket packet = (TCPPacket)in_packet; // if the IP is in the blockcache, then return if (data.BlockCache == null) { data.BlockCache = new SerializableDictionary <IPAddr, IPObj>(); } IPAddr source = packet.SourceIP; if (data.BlockCache.ContainsKey(source)) { pmr = PacketMainReturnType.Drop; return(pmr); } // checking for TTL allows us to rule out the local network // Don't check for TCP flags because we can make an educated guess that if 100+ of our ports are // fingered with a short window, we're being scanned. this will detect syn, ack, null, xmas, etc. scans. if ((!packet.Outbound) && (packet.TTL < 250) && packet.SYN && !packet.ACK) { IPObj tmp; if (ip_table == null) { ip_table = new Dictionary <IPAddr, IPObj>(); } if (ip_table.ContainsKey(source)) { tmp = (IPObj)ip_table[source]; } else { tmp = new IPObj(source); } // add the port to the ipobj, set the access time, and update the table tmp.addPort(packet.DestPort); //tmp.time(packet.PacketTime); ip_table[source] = tmp; av = tmp.getAverage(); // if they've touched more than 100 ports in less than 30 seconds and the average // packet time was less than 2s, something's wrong if (tmp.getTouchedPorts().Count >= 100 && (!tmp.Reported) && tmp.getAverage() < 2000) { pmr = PacketMainReturnType.Log | PacketMainReturnType.Allow; le = new LogEvent(String.Format(multistring.GetString("Touched Ports"), source.ToString(), tmp.getTouchedPorts().Count, tmp.getAverage()), this); LogCenter.Instance.LogEvent(le); // set the reported status of the IP address ip_table[source].Reported = true; // add the address to the potential list of IPs and to the local SESSION-BASED list if (!data.blockImmediately) { potentials.Add(source, ip_table[source]); detect.addPotential(source); } // else we want to block it immediately else { data.BlockCache.Add(source, ip_table[source]); } return(pmr); } } } catch (Exception e) { LogCenter.Instance.LogException(e); return(PacketMainReturnType.Allow); } } // This will detect UDP knockers. typically UDP scans are slower, but are combined with SYN scans // (-sSU in nmap) so we'll be sure to check for these guys too. else if (in_packet.ContainsLayer(Protocol.UDP)) { try { UDPPacket packet = (UDPPacket)in_packet; IPAddr source = packet.SourceIP; // if the source addr is in the block cache, return if (data.BlockCache.ContainsKey(source)) { return(PacketMainReturnType.Drop); } if ((!packet.Outbound) && (packet.TTL < 250) && (!packet.isDNS())) { IPObj tmp; if (ip_table.ContainsKey(source)) { tmp = (IPObj)ip_table[source]; } else { tmp = new IPObj(source); } tmp.addPort(packet.DestPort); //tmp.time(packet.PacketTime); ip_table[source] = tmp; av = tmp.getAverage(); if ((tmp.getTouchedPorts().Count >= 100) && (!tmp.Reported) && (tmp.getAverage() < 2000)) { pmr = PacketMainReturnType.Log | PacketMainReturnType.Allow; le = new LogEvent(String.Format(multistring.GetString("Touched Ports"), source.ToString(), tmp.getTouchedPorts().Count, tmp.getAverage()), this); LogCenter.Instance.LogEvent(le); ip_table[source].Reported = true; if (!data.blockImmediately) { potentials.Add(source, ip_table[source]); detect.addPotential(source); } else { data.BlockCache.Add(source, ip_table[source]); } return(pmr); } } } catch (Exception e) { LogCenter.Instance.LogException(e); return(PacketMainReturnType.Allow); } } return(PacketMainReturnType.Allow); }
/// <summary> /// Checks if an IP is local /// </summary> /// <param name="ip"></param> /// <returns></returns> private bool isLocalIP(IPAddr ip) { return (Adapter.GetAdapterInformation().IPv4.Equals(ip) || Adapter.GetAdapterInformation().IPv6.Equals(ip)); }
public void ReadXml(System.Xml.XmlReader reader) { while (!reader.IsStartElement("Blockedip")) reader.Read(); reader.ReadStartElement("Blockedip"); XmlSerializer ipSerialization = new XmlSerializer(typeof(IPAddr)); Blockedip = (IPAddr)ipSerialization.Deserialize(reader); reader.ReadEndElement(); while (!reader.IsStartElement("DateBlocked")) reader.Read(); reader.ReadStartElement("DateBlocked"); DateBlocked = (long)new XmlSerializer(typeof(long)).Deserialize(reader); reader.ReadEndElement(); while (!reader.IsStartElement("Reason")) reader.Read(); reader.ReadStartElement("Reason"); Reason = (string)new XmlSerializer(typeof(string)).Deserialize(reader); reader.ReadEndElement(); reader.ReadEndElement(); }
public TCPIPPortRule(PacketStatus ps, IPAddr ip, int port, Direction direction, bool log, bool notify) { this.ps = ps; this.direction = direction; this.port = port; this.ip = ip; this.log = log; this.notify = notify; }
private bool Contains(IPAddr ip) { return ips.Contains(ip); }
/// <summary> /// Determine whether a given IP address is blocked /// /// Note to Drone: HashSet would make this faster, even more so after IPv6 is connected everywheres /// </summary> /// <param name="i">IP address to resolve</param> /// <returns>bool</returns> private bool isIPAllowed(IPAddr i) { return(!data.BlockCache.ContainsKey(i)); }
public override void ReadXml(XmlReader reader) { XmlSerializer logSerializer = new XmlSerializer(typeof(bool)); XmlSerializer notifySerializer = new XmlSerializer(typeof(bool)); XmlSerializer intSerializer = new XmlSerializer(typeof(int)); XmlSerializer byteSerializer = new XmlSerializer(typeof(IPAddr)); reader.ReadStartElement("tcpipportrule"); reader.ReadStartElement("log"); log = (bool)logSerializer.Deserialize(reader); reader.ReadEndElement(); reader.ReadStartElement("notify"); notify = (bool)notifySerializer.Deserialize(reader); reader.ReadEndElement(); XmlSerializer dirSerializer = new XmlSerializer(typeof(Direction)); reader.ReadStartElement("direction"); direction = (Direction)dirSerializer.Deserialize(reader); reader.ReadEndElement(); XmlSerializer statusSerializer = new XmlSerializer(typeof(PacketStatus)); reader.ReadStartElement("status"); ps = (PacketStatus)statusSerializer.Deserialize(reader); reader.ReadEndElement(); reader.ReadStartElement("port"); port = ((int)intSerializer.Deserialize(reader)); reader.ReadEndElement(); reader.ReadStartElement("ip"); ip = ((IPAddr)byteSerializer.Deserialize(reader)); reader.ReadEndElement(); reader.ReadEndElement(); }
static async Task MainAsync() { Console.Title = "Audio Streamer - PC to Android"; IPAddress IPAddr; bool UseAdb = false; try { var AdbDevices = Process.Start(new ProcessStartInfo() { FileName = "adb", Arguments = "devices", UseShellExecute = false, RedirectStandardOutput = true }); await AdbDevices.StandardOutput.ReadLineAsync(); UseAdb = !string.IsNullOrWhiteSpace(await AdbDevices.StandardOutput.ReadLineAsync()); } catch (System.ComponentModel.Win32Exception) { } if (UseAdb) { IPAddr = IPAddress.Loopback; } else { Console.Write("IP: "); IPAddr = IPAddress.Parse(Console.ReadLine()); } Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.High; using (Capture = new WasapiLoopbackCapture(0, new CSCore.WaveFormat(), ThreadPriority.Highest)) { while (true) { var NoSpamDelay = Task.Delay(1000); if (UseAdb) { Process.Start(new ProcessStartInfo() { FileName = "adb", Arguments = "forward tcp:1420 tcp:1420", UseShellExecute = false }); } using (var Conn = new TcpClient() { NoDelay = true, ReceiveBufferSize = 64, SendBufferSize = 1 << 12 //2^12 = ~4000 so 1000 floats }) { try { await Conn.ConnectAsync(IPAddr, ServerPort); Stream = Conn.GetStream(); if (Stream.ReadByte() == 1) { Console.WriteLine("Connected to " + IPAddr.ToString()); Capture.Initialize(); using (Source = new SoundInSource(Capture)) { int SampleRateServer = Source.WaveFormat.SampleRate; int SampleRateClient = Stream.ReadByte() | Stream.ReadByte() << 8 | Stream.ReadByte() << 16; if (SampleRateClient != SampleRateServer) { Console.WriteLine($"Sample rate mismatch, PC was {SampleRateServer} Hz but client was {SampleRateClient} Hz"); Console.WriteLine("Adjust your PC's sample rate then press any key to try again"); Console.ReadKey(); Console.Clear(); } else { // Start Capturing Source.DataAvailable += DataAvailable; Capture.Start(); Console.WriteLine($"Started recording audio at {SampleRateServer} Hz"); Window.SetWindowShown(false); // Stop Capturing await(DisconnectWaiter = new TaskCompletionSource <bool>()).Task; await Task.Run(() => Capture.Stop()); Window.SetWindowShown(true); Console.WriteLine("Disconnected, stopped recording audio"); } } } } catch { } await NoSpamDelay; } } } }
public override PacketMainReturnType interiorMain(ref Packet in_packet) { if (in_packet.GetHighestLayer() == Protocol.ARP) { ARPPacket arpp = (ARPPacket)in_packet; if (arpp.isRequest && arpp.Outbound) { IPAddr ip = new IPAddr(arpp.ATargetIP.GetAddressBytes()); if (!requestedIPs.Contains(ip)) requestedIPs.Add(ip); } else if (!arpp.Outbound) { IPAddr ip = new IPAddr(arpp.ASenderIP.GetAddressBytes()); if (!arpp.isRequest) { if (requestedIPs.Contains(ip)) { lock (padlock) { if (data.arpCache.ContainsKey(new IPAddr(arpp.ASenderIP.GetAddressBytes()))) { if (!Utility.ByteArrayEq(data.arpCache[new IPAddr(arpp.ASenderIP.GetAddressBytes())].AddressBytes, arpp.ASenderMac)) { PacketMainReturnType pmr = 0; if (data.RectifyAttacks) pmr = PacketMainReturnType.Edited; else pmr = PacketMainReturnType.Drop; if (data.LogAttacks) { LogEvent le = new LogEvent(String.Format(multistring.GetString("Response does not equal cache"), new PhysicalAddress(arpp.ASenderMac).ToString(), arpp.ASenderIP.ToString()), this); le.PMR = PacketMainReturnType.Log | PacketMainReturnType.Popup; LogCenter.Instance.LogEvent(le); } if (data.RectifyAttacks) { arpp.ATargetIP = arpp.ASenderIP; arpp.ATargetMac = data.arpCache[new IPAddr(arpp.ATargetIP.GetAddressBytes())].AddressBytes; arpp.ASenderMac = this.Adapter.GetAdapterInformation().InterfaceInformation.GetPhysicalAddress().GetAddressBytes(); arpp.FromMac = arpp.ASenderMac; arpp.ToMac = arpp.ATargetMac; arpp.ASenderIP = Adapter.GetAdapterInformation().IPv4; arpp.Outbound = true; in_packet = arpp; } return pmr; } else { requestedIPs.Remove(ip); } } else { data.arpCache[new IPAddr(arpp.ASenderIP.GetAddressBytes())] = new MACAddr(arpp.ASenderMac); if (UpdatedArpCache != null) UpdatedArpCache(); requestedIPs.Remove(ip); } } } else { lock (padlock) { if (data.arpCache.ContainsKey(new IPAddr(arpp.ASenderIP.GetAddressBytes()))) { if (!Utility.ByteArrayEq(data.arpCache[new IPAddr(arpp.ASenderIP.GetAddressBytes())].AddressBytes, arpp.ASenderMac)) { PacketMainReturnType pmra = 0; if (data.RectifyAttacks) pmra = PacketMainReturnType.Edited; else pmra = PacketMainReturnType.Drop; if (data.LogAttacks) { LogEvent le = new LogEvent(String.Format(multistring.GetString("Response does not equal cache"), new PhysicalAddress(arpp.ASenderMac).ToString(), arpp.ASenderIP.ToString()), this); le.PMR = PacketMainReturnType.Log | PacketMainReturnType.Popup; LogCenter.Instance.LogEvent(le); } if (data.RectifyAttacks) { arpp.ATargetIP = arpp.ASenderIP; arpp.ATargetMac = data.arpCache[new IPAddr(arpp.ATargetIP.GetAddressBytes())].AddressBytes; arpp.ASenderMac = this.Adapter.GetAdapterInformation().InterfaceInformation.GetPhysicalAddress().GetAddressBytes(); arpp.FromMac = arpp.ASenderMac; arpp.ToMac = arpp.ATargetMac; arpp.ASenderIP = Adapter.GetAdapterInformation().IPv4; arpp.Outbound = true; in_packet = arpp; } return pmra; } } } PacketMainReturnType pmr = 0; pmr = PacketMainReturnType.Drop; if (data.LogUnsolic) { LogEvent le2 = new LogEvent(String.Format(multistring.GetString("Unsolicited"), new PhysicalAddress(arpp.ASenderMac).ToString(), arpp.ASenderIP.ToString()), this); le2.PMR = PacketMainReturnType.Log; } return pmr; } } else { lock (padlock) { if (data.arpCache.ContainsKey(new IPAddr(arpp.ASenderIP.GetAddressBytes()))) { if (!Utility.ByteArrayEq(data.arpCache[new IPAddr(arpp.ASenderIP.GetAddressBytes())].AddressBytes, arpp.ASenderMac)) { PacketMainReturnType pmr = PacketMainReturnType.Drop; if (data.LogAttacks) { LogEvent le = new LogEvent(String.Format(multistring.GetString("Response does not equal cache"), new PhysicalAddress(arpp.ASenderMac).ToString(), arpp.ASenderIP.ToString()), this); le.PMR = PacketMainReturnType.Log | PacketMainReturnType.Popup; LogCenter.Instance.LogEvent(le); } return pmr; } } } } return 0; } return 0; } return 0; }