Esempio n. 1
0
        void pasiveScan_NewARP(object sender, Core.ArpEventArgs e)
        {
            if (e.p == null)
            {
                return;
            }
            Packet p = e.p;

            if (!(p.PayloadPacket is ARPPacket))
            {
                return;
            }

            ARPPacket arp = (ARPPacket)p.PayloadPacket;


            foreach (Data.Attack attack in attacks.Where(A => A.attackType == Data.AttackType.InvalidMacSpoofIpv4 && A.attackStatus == Data.AttackStatus.Attacking))
            {
                if (attack is InvalidMacSpoofAttackIpv4Attack)
                {
                    InvalidMacSpoofAttackIpv4Attack spoofAttack = (InvalidMacSpoofAttackIpv4Attack)attack;
                    if ((spoofAttack.t1.mac.Equals(arp.SenderHardwareAddress)) && arp.TargetProtocolAddress.Equals(spoofAttack.t2.ip))
                    {
                        ForceAttack(spoofAttack);
                    }
                }
            }
        }
Esempio n. 2
0
        private void Attack()
        {
            while (true)
            {
                try
                {
                    PhysicalAddress MACLocal = device.MacAddress;
                    EthernetPacket  ethernet;

                    foreach (Data.Attack attack in attacks.Where(A => A.attackType == Data.AttackType.ARPSpoofing && A.attackStatus == Data.AttackStatus.Attacking))
                    {
                        if (attack is MitmAttack)
                        {
                            ethernet = GenerateResponseArpPoison(device.Interface.MacAddress,
                                                                 ((MitmAttack)attack).t1.mac,
                                                                 ((MitmAttack)attack).t1.ip,
                                                                 ((MitmAttack)attack).t2.ip);
                            Program.CurrentProject.data.SendPacket(ethernet);

                            ethernet = GenerateResponseArpPoison(device.Interface.MacAddress,
                                                                 ((MitmAttack)attack).t2.mac,
                                                                 ((MitmAttack)attack).t2.ip,
                                                                 ((MitmAttack)attack).t1.ip);
                            Program.CurrentProject.data.SendPacket(ethernet);
                        }
                    }

                    foreach (Data.Attack attack in attacks.Where(A => A.attackType == Data.AttackType.ARPSpoofing && A.attackStatus == Data.AttackStatus.Stopping))
                    {
                        if (attack is MitmAttack)
                        {
                            ethernet = new EthernetPacket(device.Interface.MacAddress, ((MitmAttack)attack).t1.mac, EthernetPacketType.Arp);
                            ethernet.PayloadPacket = new ARPPacket(ARPOperation.Response, ((MitmAttack)attack).t1.mac, ((MitmAttack)attack).t1.ip, ((MitmAttack)attack).t2.mac, ((MitmAttack)attack).t2.ip);
                            Program.CurrentProject.data.SendPacket(ethernet);

                            ethernet = new EthernetPacket(device.Interface.MacAddress, ((MitmAttack)attack).t2.mac, EthernetPacketType.Arp);
                            ethernet.PayloadPacket = new ARPPacket(ARPOperation.Response, ((MitmAttack)attack).t2.mac, ((MitmAttack)attack).t2.ip, ((MitmAttack)attack).t1.mac, ((MitmAttack)attack).t1.ip);
                            Program.CurrentProject.data.SendPacket(ethernet);

                            attack.attackStatus = Data.AttackStatus.Stop;
                        }
                    }

                    Thread.Sleep(SendPacketEachXSecs * 1000);
                }
                catch (ThreadAbortException)
                {
                    return;
                }
                catch
                {
                }
            }
        }
Esempio n. 3
0
 public IWebSocketConnection GetConnection(string id)
 {
     try
     {
         _readerWriterLockSlim.EnterReadLock();
         return(_connections.Where(x => x.Id == id).FirstOrDefault());
     }
     finally
     {
         _readerWriterLockSlim.ExitReadLock();
     }
 }
Esempio n. 4
0
        /// <summary>
        /// 注册Ajax节点
        /// </summary>
        /// <param name="node"></param>
        /// <param name="e"></param>
        private void AjaxMark(HtmlElement node, EventHandler e)
        {
            if (_ajaxSet == null)
            {
                _ajaxSet    = new SynchronizedCollection <Tuple <HtmlElement, EventHandler> >();
                _ajaxRaiser = new JobTimer(state =>
                {
                    foreach (var item in _ajaxSet.Where(p => p.Item1.GetAttribute(AjaxBlockEntity.AjaxBlock) == "0").ToArray())
                    {
                        item.Item2(item.Item1, EventArgs.Empty);
                    }
                }, Timeout.InfiniteTimeSpan)
                {
                    AutoDispose = false
                };
            }
            node.SetAttribute(AjaxBlockEntity.AjaxBlock, "0");
            var q = from t in _ajaxSet
                    where t.Item1 == node
                    select t;
            var tuple = q.SingleOrDefault();

            if (tuple != null)
            {
                _ajaxSet.Remove(tuple);
            }
            _ajaxSet.Add(Tuple.Create(node, e));
        }
Esempio n. 5
0
        private DataRow[] ParseQuery(string txt)
        {
            if (txt.Length > 0 && persons != null)
            {
                txt = Replacer.ReplaceRusLat(txt);
                string[] w = Regex.Split(txt, @"\s+");

                if (w.Length > 0)
                {
                    List <DataRow> result = persons.Where(x =>
                                                          x[Environment.PersonsUsedData.NameRLField].ToString().ToLower().StartsWith(w[0].ToLower())).ToList();
                    for (int i = 1; i < w.Length && result.Count > 0; i++)
                    {
                        result = result.Where(x =>
                                              x[Environment.PersonsUsedData.NameRLField].ToString().ToLower().Contains(" " + w[i].ToLower())).ToList();
                    }

                    if (result.Count > 0)
                    {
                        return(result.ToArray());
                    }
                }
            }

            return(null);
        }
        private void combo1_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                combo2.Items.Clear();
                combo2.Items.Add("[" + Environment.StringResources.GetString("Absent") + "]");

                // filling combo2

                foreach (KeyValuePair <string, string> t in groupNames.Where(t => combo1.Text != t.Value))
                {
                    combo2.Items.Add(t.Value);
                    if (goBuf != null && goBuf.Length >= 2)
                    {
                        // 2nd combo check
                        if (goBuf.Substring(1, 1) == t.Key)
                        {
                            combo2.SelectedIndex = combo2.Items.Count - 1;
                        }
                    }
                }

                if (combo2.Text == "")
                {
                    combo2.SelectedIndex = 0;
                }
            }
            catch (Exception ex)
            {
                Lib.Win.Data.Env.WriteToLog(ex);
            }
        }
            public T Get(string identifier)
            {
                lock (getLock)
                {
                    // Check the cache
                    var entry = _cache.Where(ce => ce.Identifier == identifier).SingleOrDefault();

                    // Remove entry if it's too old
                    if (entry != null && entry.Expired)
                    {
                        _cache.Remove(entry);
                        entry = null;
                    }

                    // If we still have a fresh entry, return it
                    if (entry != null)
                    {
                        return(entry.Data);
                    }
                    else
                    {
                        // Otherwise, fetch it and cache it.
                        T newData = default(T);

                        newData = _onCacheMiss(identifier);
                        _cache.Add(new CacheEntry <T> {
                            Data = newData, Identifier = identifier, Expires = DateTime.Now.AddSeconds(_duration)
                        });

                        return(newData);
                    }
                }
            }
Esempio n. 8
0
        public void RecreateSingleTag(int?id)
        {
            Tag tag = _tags.Where(x => x.Id == id).SingleOrDefault();

            if (tag != null)
            {
                lock (_locker)
                {
                    var decisions = _decisions.ToList();
                    var existing  = _decisionTags.Where(x => x.TagId == id);
                    Parallel.ForEach(existing, existingTag =>
                    {
                        _decisionTags.Remove(existingTag);
                    });

                    Parallel.ForEach(_decisions, dec =>
                    {
                        if (Regex.IsMatch(dec.Content, tag.RegExp, RegexOptions.IgnoreCase))
                        {
                            DecisionTag dt = new DecisionTag()
                            {
                                DecisionId = dec.Id,
                                TagId      = tag.Id
                            };
                            _decisionTags.Add(dt);
                        }
                    });
                }
            }
        }
Esempio n. 9
0
 public void Verify()
 {
     if (docIDs.Count > 0 || fileNames.Count > 0)
     {
         var sb = new StringBuilder();
         sb.Append(Environment.StringResources.GetString("NewWindowDefaultToolTip"));
         foreach (KeyValuePair <int, string> t in docIDs.Where(t => t.Key > 0))
         {
             sb.Append("\n");
             sb.Append(t.Value);
         }
         foreach (KeyValuePair <string, string> t in fileNames)
         {
             sb.Append("\n");
             sb.Append(t.Value);
         }
         tooltip.SetToolTip(this, sb.ToString());
         Text    = string.Empty;
         Visible = true;
         Enabled = true;
     }
     else
     {
         tooltip.RemoveAll();
         Visible = false;
         Enabled = false;
     }
 }
Esempio n. 10
0
        private List <(string tableName, string conString, DatabaseType dbType)> GetTargetTables
            (string absTableName, ReadWriteType opType, string absDbName, object obj = null)
        {
            //获取抽象数据库
            AbstractDatabase db = null;

            if (absDbName.IsNullOrEmpty())
            {
                db = _absDb.Single();
            }
            else
            {
                db = _absDb.Where(x => x.AbsDbName == absDbName).Single();
            }
            if (db == null)
            {
                throw new Exception("请配置抽象数据库");
            }

            //获取抽象数据表
            var absTable = db.Tables.Where(x => x.AbsTableName == absDbName).Single();

            //获取物理表
            List <(string physicTableName, string dataSourceName)> physicTables = null;

            //读操作获取全部表
            if (opType == ReadWriteType.Read)
            {
                physicTables = absTable.PhysicTables;
            }
            else
            {
                //找特定表
                if (!obj.IsNullOrEmpty())
                {
                    var theTable = absTable.FindTable(obj);
                    physicTables = absTable.PhysicTables.Where(x => x.physicTableName == theTable).ToList();
                }
                //所有表
                else
                {
                    physicTables = absTable.PhysicTables;
                }
            }

            //获取数据源
            var dataSources = _dataSource
                              .Where(x => physicTables.Select(y => y.dataSourceName).Contains(x.DataSourceName))
                              .Select(x => new { x.DataSourceName, x.DbType, RandomHelper.Next(x.Dbs.Where(y => y.opType.HasFlag(opType)).ToList()).conString })
                              .ToList();

            var q = from a in physicTables
                    join b in dataSources on a.dataSourceName equals b.DataSourceName
                    select(a.physicTableName, b.conString, b.DbType);

            var resList = q.ToList();

            return(resList);
        }
Esempio n. 11
0
 public void CancelPending()
 {
     lock (_queueSimpleOperation.SyncRoot)
         _queueSimpleOperation.Where(op => op.OperationStatus == FileOperationStatus.Waiting).ToList().ForEach(op => op.Abort());
     lock (_queueConvertOperation.SyncRoot)
         _queueConvertOperation.Where(op => op.OperationStatus == FileOperationStatus.Waiting).ToList().ForEach(op => op.Abort());
     lock (_queueExportOperation.SyncRoot)
         _queueExportOperation.Where(op => op.OperationStatus == FileOperationStatus.Waiting).ToList().ForEach(op => op.Abort());
     Logger.Trace("Cancelled pending operations");
 }
Esempio n. 12
0
        /// <summary>
        /// Run query for logged event based on criteria in EventInfo
        /// </summary>
        /// <param name="eventInfo"></param>
        /// <returns></returns>
        private LoggedEvent RunQuery(EventInfo eventInfo)
        {
            LoggedEvent loggedEvent           = null;
            IEnumerable <LoggedEvent> results = null;

            if (eventInfo.EventId >= 0) // kind of silly, but...
            {
                // select with minimun info
                results = EventLogEntries.Where(e => e.Observed == false &&
                                                e.LogEntry.EventID == eventInfo.EventId &&
                                                e.LogEntry.EntryType == eventInfo.EventType);

                // Event source populated?
                if (!string.IsNullOrWhiteSpace(eventInfo.EventSource))
                {
                    results = results.Where(e => e.LogEntry.Source == eventInfo.EventSource);
                }


                // EventMEssage populated?
                if (!string.IsNullOrWhiteSpace(eventInfo.EventMessage))
                {
                    results = results.Where(e => e.LogEntry.Message.Contains(eventInfo.EventMessage));
                }

                loggedEvent = results.DefaultIfEmpty(null).FirstOrDefault();
            }
            else
            {
                TraceWriteLn("Event lacks basic criteria for query (min: EventId >= 0)");
                // set as never found
                loggedEvent = null;
            }

            return(loggedEvent);
        }
Esempio n. 13
0
        private void Attack()
        {
            while (true)
            {
                try
                {
                    PhysicalAddress MACLocal = device.MacAddress;

                    foreach (Data.Attack attack in attacks.Where(A => A.attackType == Data.AttackType.NeighborAdvertisementSpoofing && A.attackStatus == Data.AttackStatus.Attacking))
                    {
                        if (attack is MitmAttack)
                        {
                            SendNeighborAdvertisement(((MitmAttack)attack).t1.ip, MACLocal, ((MitmAttack)attack).t2.ip, ((MitmAttack)attack).t2.mac);
                            SendNeighborAdvertisement(((MitmAttack)attack).t2.ip, MACLocal, ((MitmAttack)attack).t1.ip, ((MitmAttack)attack).t1.mac);
                        }
                    }

                    foreach (Data.Attack attack in attacks.Where(A => A.attackType == Data.AttackType.NeighborAdvertisementSpoofing && A.attackStatus == Data.AttackStatus.Stopping))
                    {
                        SendNeighborAdvertisement(((MitmAttack)attack).t1.ip, ((MitmAttack)attack).t1.mac, ((MitmAttack)attack).t2.ip, ((MitmAttack)attack).t2.mac);
                        SendNeighborAdvertisement(((MitmAttack)attack).t2.ip, ((MitmAttack)attack).t2.mac, ((MitmAttack)attack).t1.ip, ((MitmAttack)attack).t1.mac);

                        attack.attackStatus = Data.AttackStatus.Stop;
                    }

                    Thread.Sleep(SendPacketEachXSecs * 1000);
                }
                catch (ThreadAbortException)
                {
                    return;
                }
                catch
                {
                }
            }
        }
Esempio n. 14
0
        public bool CheckIfHijack(Packet p)
        {
            foreach (Data.Attack attack in attacks.Where(A => A.attackType == Data.AttackType.DNSHijacking && A.attackStatus == Data.AttackStatus.Attacking))
            {
                if ((p.PayloadPacket != null && p.PayloadPacket.PayloadPacket != null) && (p.PayloadPacket.PayloadPacket is UdpPacket))
                {
                    EthernetPacket ethernet = (EthernetPacket)p;
                    IpPacket       ip       = (IpPacket)p.PayloadPacket;
                    UdpPacket      udp      = (UdpPacket)p.PayloadPacket.PayloadPacket;

                    if ((udp.SourcePort == 53)) // La respuesta DNS
                    {
                        // Comprobamos que venga a nuestra MAC pero no a nuestra IP
                        if (NeedToRoute(ip))
                        {
                            try
                            {
                                Heijden.DNS.Response response  = new Heijden.DNS.Response(new IPEndPoint(IPAddress.Parse("1.2.3.4"), 53), udp.PayloadData);
                                DNSHijackAttack      dnsAttack = (DNSHijackAttack)attack;

                                foreach (Heijden.DNS.Question q in response.Questions)
                                {
                                    if ((q.QName == dnsAttack.domain + ".") || dnsAttack.domain == "*")
                                    {
                                        return(true);
                                    }
                                }
                            }
                            catch
                            {
                                return(false);
                            }
                        }
                        else
                        {
                            return(false);
                        }
                    }
                }
            }
            return(false);
        }
Esempio n. 15
0
        private void HandleChat(NetworkClient client, NetDataReader reader)
        {
            var chatMessage        = reader.GetString();
            var clientWorldId      = client.WorldId;
            var clientsInSameWorld = _clients
                                     .Where(c => c.WorldId == clientWorldId && c.Id != client.Id)
                                     .ToArray();

            if (clientsInSameWorld.Any())
            {
                var writer = _writerPool.Get();
                writer.Put(PacketIds.S2C.Chat);
                writer.Put(chatMessage);
                foreach (var clientInSameWorld in clientsInSameWorld)
                {
                    clientInSameWorld.Send(writer);
                }
                _writerPool.Return(writer);
            }
        }
Esempio n. 16
0
        private void FormSelectIPs_Load(object sender, EventArgs e)
        {
            listViewNeighbors.FullRowSelect = true;
            listViewNeighbors.MultiSelect   = multiSelect;

            foreach (Neighbor neighbor in lstNeighbors)
            {
                foreach (IPAddress ip in neighbor.GetIPs())
                {
                    if ((lstIpsFiltered != null) && (lstIpsFiltered.Contains(ip)))
                    {
                        continue;
                    }

                    ListViewItem lvi = new ListViewItem(ip.ToString());
                    lvi.Tag = ip;

                    if (lstPrevIpsFiltered != null)
                    {
                        if (lstPrevIpsFiltered.Where(I => I.Equals(ip)).Count() > 0)
                        {
                            lvi.Selected = true;
                        }
                    }

                    if ((type == PanelTargets.TypeList.Ipv4) && (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork))
                    {
                        lvi.SubItems.Add("IPv4");
                        listViewNeighbors.Items.Add(lvi);
                    }
                    else if ((type == PanelTargets.TypeList.Ipv6) && (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6))
                    {
                        lvi.SubItems.Add("IPv6");
                        listViewNeighbors.Items.Add(lvi);
                    }
                }
            }
        }
Esempio n. 17
0
        private void AnalyzeLLMNR(Packet packet)
        {
            if (!(packet is EthernetPacket))
            {
                return;
            }

            // IPv4 y IPv6
            if (packet.PayloadPacket.PayloadPacket is UdpPacket)
            {
                // Respuestas de LLMNR. De aqui podemos capturar el nombre.
                if ((((UdpPacket)(packet.PayloadPacket.PayloadPacket)).SourcePort == 5355) && (((EthernetPacket)packet).Type == EthernetPacketType.IpV4))
                {
                    LLMNR.LLMNRAnswer LLMNRAnswer = new LLMNR.LLMNRAnswer(packet.PayloadPacket.PayloadPacket.PayloadData);

                    //  Solo lo cojemos las respuestas que son de tipo PTR o de tipo A
                    if (LLMNRAnswer.isPtrResponse == true && LLMNRAnswer.computerName != string.Empty)
                    {
                        Neighbor neighbor = Program.CurrentProject.data.GetNeighbor(((EthernetPacket)(packet)).SourceHwAddress);

                        if (neighbor == null)
                        {
                            neighbor = new Neighbor();
                            neighbor.computerName = LLMNRAnswer.computerName;
                            neighbor.AddIP(LLMNRAnswer.ipAddress);
                            neighbor.physicalAddress = ((EthernetPacket)(packet)).SourceHwAddress;
                            Program.CurrentProject.data.AddNeighbor(neighbor);
                            NewNeighbor(this, new NeighborEventArgs(neighbor));
                        }
                        else
                        {
                            neighbor.computerName = LLMNRAnswer.computerName;
                            Program.CurrentProject.data.AddNeighbor(neighbor);
                        }
                    }
                }


                if ((((EthernetPacket)packet).Type == EthernetPacketType.IpV4) && (((UdpPacket)(packet.PayloadPacket.PayloadPacket)).DestinationPort == 5355))
                {
                    SynchronizedCollection <Attack> lstAttacks = Program.CurrentProject.data.GetAttacks();

                    // En caso de MITM ARP -> Si el equipo está intentando restablecer su tabla ARP ... se le vuelve a envenenar
                    foreach (Attack attk in lstAttacks.Where(A => A.attackType == AttackType.WpadIPv4 && A.attackStatus == AttackStatus.Attacking))
                    {
                        MitmAttack mitmAtt = (MitmAttack)attk;
                        if (((IPv4Packet)((EthernetPacket)packet).PayloadPacket).SourceAddress.Equals(mitmAtt.t2.ip))
                        {
                            WpadIPv4Attack.Instance.GenerateLLMNRResponse(packet);
                        }
                    }
                }

                if ((((EthernetPacket)packet).Type == EthernetPacketType.IpV6) && (((UdpPacket)(packet.PayloadPacket.PayloadPacket)).DestinationPort == 5355))
                {
                    SynchronizedCollection <Attack> lstAttacks = Program.CurrentProject.data.GetAttacks();

                    // En caso de MITM ARP -> Si el equipo está intentando restablecer su tabla ARP ... se le vuelve a envenenar
                    foreach (Attack attk in lstAttacks.Where(A => A.attackType == AttackType.WpadIPv6 && A.attackStatus == AttackStatus.Attacking))
                    {
                        MitmAttack mitmAtt = (MitmAttack)attk;
                        if (((IPv6Packet)((EthernetPacket)packet).PayloadPacket).SourceAddress.Equals(mitmAtt.t2.ip))
                        {
                            WpadIPv6Attack.Instance.GenerateLLMNRResponse(packet);
                        }
                    }
                }
            }
        }
Esempio n. 18
0
        private void StartServer()
        {
            const string LOG_TAG_PREFIX = "ApplicationServer::StartServer::";

            AggregateException ex = null;

            this.ReinitTrustedCompositionCatalog();

            // assemblies with services
            {
                var serviceDir = new DirectoryInfo(Path.Combine(this.WorkingDirectory, "services")).CreateDirectoryDeep();

                this.LoadAndAddTrustedAssemblies(serviceDir.GetFiles("*.dll"),
                                                 LOG_TAG_PREFIX);
            }

            // assemblies with functions
            {
                var funcDir = new DirectoryInfo(Path.Combine(this.WorkingDirectory, "funcs")).CreateDirectoryDeep();

                this.LoadAndAddTrustedAssemblies(funcDir.GetFiles("*.dll"),
                                                 LOG_TAG_PREFIX);
            }

            // web interface
            {
                IList <Assembly> webInterfaceAssemblies = new SynchronizedCollection <Assembly>();

                var webDir = new DirectoryInfo(Path.Combine(this.WorkingDirectory, "web")).CreateDirectoryDeep();
                this.LoadAndAddTrustedAssemblies(webDir.GetFiles("*.dll"),
                                                 LOG_TAG_PREFIX);

                try
                {
                    this.DisposeOldWebInterfaceServer();

                    //TODO read from configuration
                    var newWebInterfaceServer = ServiceLocator.Current.GetInstance <IHttpServer>();
                    {
                        // HTTPs ?
                        {
                            bool?useHttps;
                            this.StartupConfig
                            .TryGetValue <bool?>(category: CONFIG_CATEGORY_WEBINTERFACE,
                                                 name: CONFIG_VALUE_USE_HTTPS,
                                                 value: out useHttps,
                                                 defaultVal: DEFAULT_CONFIG_VALUE_USE_HTTPS);

                            newWebInterfaceServer.UseSecureHttp = useHttps ?? DEFAULT_CONFIG_VALUE_USE_HTTPS;
                        }

                        // TCP port
                        {
                            int?port;
                            this.StartupConfig
                            .TryGetValue <int?>(category: CONFIG_CATEGORY_WEBINTERFACE,
                                                name: CONFIG_VALUE_PORT,
                                                value: out port,
                                                defaultVal: DEFAULT_CONFIG_VALUE_WEBINTERFACE_PORT);

                            newWebInterfaceServer.Port = port ?? DEFAULT_CONFIG_VALUE_WEBINTERFACE_PORT;
                        }

                        if (newWebInterfaceServer.UseSecureHttp)
                        {
                            // SSL thumbprint
                            {
                                newWebInterfaceServer.SetSslCertificateByThumbprint(this.StartupConfig
                                                                                    .GetValue <IEnumerable <char> >(category: CONFIG_CATEGORY_WEBINTERFACE,
                                                                                                                    name: CONFIG_VALUE_SSL_THUMBPRINT));
                            }
                        }
                    }

                    var newHandler = new WebInterfaceHandler(this, newWebInterfaceServer);
                    this._webHandler = newHandler;

                    newHandler.Start();
                }
                catch (Exception e)
                {
                    this.Logger
                    .Log(msg: e.GetBaseException() ?? e,
                         tag: LOG_TAG_PREFIX + "WebInterface",
                         categories: LoggerFacadeCategories.Errors);

                    this.DisposeOldWebInterfaceServer();
                }
            }

            var moduleList = this.Modules;

            if (moduleList != null)
            {
                ex = moduleList.OfType <global::System.IDisposable>()
                     .ForAllAsync(ctx =>
                {
                    var m         = ctx.Item;
                    var doDispose = true;

                    var dispObj = m as ITMDisposable;
                    if (dispObj != null)
                    {
                        doDispose = !dispObj.IsDisposed;
                    }

                    if (doDispose)
                    {
                        m.Dispose();
                    }
                }, throwExceptions: false);
            }

            if (ex != null)
            {
                this.Logger
                .Log(msg: ex,
                     tag: LOG_TAG_PREFIX + "UnloadOldModules",
                     categories: LoggerFacadeCategories.Errors);
            }

            IList <IAppServerModule> newModules = new SynchronizedCollection <IAppServerModule>();

            var modDir = new DirectoryInfo(Path.Combine(this.WorkingDirectory, "modules")).CreateDirectoryDeep();
            {
                ex = modDir.GetFiles("*.dll")
                     .ForAllAsync(ctx =>
                {
                    var f = ctx.Item;

                    var trustedCatalog = ctx.State.CompositionCatalog.Clone(cloneCatalogData: true);
                    var asmName        = AssemblyName.GetAssemblyName(f.FullName);
                    if (!trustedCatalog.IsTrustedAssembly(asmName))
                    {
#if DEBUG
                        var s = string.Format("INSERT INTO [Security].[TrustedAssemblies] (TrustedAssemblyKey, Name) VALUES (0x{0}, N'{1}');",
                                              asmName.GetPublicKey().AsHexString(),
                                              asmName.FullName);
#endif
                        ctx.State
                        .Logger
                        .Log(categories: LoggerFacadeCategories.Warnings,
                             msg: string.Format("'{0}' is no trusted module!",
                                                f.FullName));

                        return;
                    }

                    var asmBlob = File.ReadAllBytes(f.FullName);
                    var asm     = Assembly.Load(asmBlob);

                    trustedCatalog.AddAssembly(asm);

                    CompositionContainer container;
                    DelegateServiceLocator serviceLocator;
                    {
                        var catalog = new AggregateCatalog();
                        catalog.Catalogs.Add(trustedCatalog);

                        container = new CompositionContainer(catalog,
                                                             isThreadSafe: true);

                        serviceLocator = new DelegateServiceLocator(new ExportProviderServiceLocator(container));
                    }

                    var modules = serviceLocator.GetAllInstances <IAppServerModule>().AsArray();
                    if (modules.Length == 1)
                    {
                        CompositionHelper.ComposeExportedValueEx(container,
                                                                 modules[0]);
                    }
                    else
                    {
                        foreach (var m in modules)
                        {
                            CompositionHelper.ComposeExportedValue(container,
                                                                   m,
                                                                   m.GetType());
                        }
                    }

                    modules.ForAll(ctx2 =>
                    {
                        var m = ctx2.Item;
                        if (m.IsInitialized)
                        {
                            // no need to initialize
                            return;
                        }

                        //TODO: add implementation(s)
                        var logger = new AggregateLogger();

                        var moduleRootDir = new DirectoryInfo(Path.Combine(ctx2.State.ModuleDirectory,
                                                                           m.Name)).CreateDirectoryDeep();

                        var moduleCtx    = new SimpleAppServerModuleContext(m);
                        moduleCtx.Config = new IniFileConfigRepository(Path.Combine(moduleRootDir.FullName,
                                                                                    "config.ini"));
                        moduleCtx.InnerServiceLocator = ctx2.State.ServiceLocator;
                        moduleCtx.Logger       = logger;
                        moduleCtx.OtherModules = ctx2.State.AllModules
                                                 .Where(CreateWherePredicateForExtractingOtherModules(m));
                        moduleCtx.SetAssemblyFile(ctx2.State.AssemblyFile.FullName);

                        var moduleInitCtx           = new SimpleAppServerModuleInitContext();
                        moduleInitCtx.ModuleContext = moduleCtx;
                        moduleInitCtx.RootDirectory = moduleRootDir.FullName;

                        m.Initialize(moduleInitCtx);

                        ctx2.State
                        .NewModules
                        .Add(m);
                    }, actionState: new
                    {
                        AllModules      = modules,
                        AssemblyFile    = f,
                        ModuleDirectory = ctx.State.ModuleDirectory,
                        NewModules      = ctx.State.NewModules,
                        ServiceLocator  = serviceLocator,
                    }, throwExceptions: true);
                }, actionState: new
                {
                    CompositionCatalog = this.TrustedCompositionCatalog
                                         .Clone(cloneCatalogData: false),
                    Logger          = this.Logger,
                    ModuleDirectory = modDir.FullName,
                    NewModules      = newModules,
                }, throwExceptions: false);

                if (ex != null)
                {
                    this.Logger
                    .Log(msg: ex,
                         tag: LOG_TAG_PREFIX + "LoadModules",
                         categories: LoggerFacadeCategories.Errors);
                }
            }

            this.Modules = newModules.Where(m => m.IsInitialized)
                           .ToArray();

            if (this.Modules.Length > 0)
            {
                this.Logger
                .Log(msg: string.Format("{0} modules were loaded.", this.Modules.Length),
                     tag: LOG_TAG_PREFIX + "LoadModules",
                     categories: LoggerFacadeCategories.Information);
            }
            else
            {
                this.Logger
                .Log(msg: "No module was loaded.",
                     tag: LOG_TAG_PREFIX + "LoadModules",
                     categories: LoggerFacadeCategories.Warnings);
            }

            this.RefreshEntityAssemblyList();

            ex = newModules.Where(m => m.CanStart &&
                                  m.IsInitialized)
                 .ForAllAsync(ctx =>
            {
                var m = ctx.Item;

                m.Start();
            }, throwExceptions: false);

            if (ex != null)
            {
                this.Logger
                .Log(msg: ex,
                     tag: LOG_TAG_PREFIX + "StartModules",
                     categories: LoggerFacadeCategories.Errors);
            }
        }
Esempio n. 19
0
        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 IPv4Packet))
            {
                return;
            }

            IPv4Packet packetIpLayer = (IPv4Packet)udp.ParentPacket;

            if (udp.PayloadData.Length < sizeof(DHCP.bootp))
            {
                return;
            }
            DHCP.bootp *dhcp = (DHCP.bootp *)Marshal.UnsafeAddrOfPinnedArrayElement(udp.PayloadData, 0).ToPointer();

            DHCP.RequestedIP optionRequestedIP       = new DHCP.RequestedIP();
            bool             existsOptionRequestedIP = false;

            DHCP.ServerID optionServerID       = new DHCP.ServerID();
            bool          existsOptionServerID = false;
            string        Strname = string.Empty;

            ushort bp_vend_len = (ushort)(udp.Length - Marshal.SizeOf(*dhcp) + 4);
            uint   pos         = 4;

            while (pos < bp_vend_len)
            {
                byte option = dhcp->bp_vend[pos];
                if (option == 0xff)
                {
                    break;
                }
                byte len = dhcp->bp_vend[pos + 1];
                switch (option)
                {
                case DHCP.TAG_DHCP_MESSAGE:
                {
                    DHCP.MessageType *mtype = (DHCP.MessageType *)(dhcp->bp_vend + pos);
                    //We save the real DHCP IP
                    if (mtype->type == DHCP.DHCPACK && packetIpLayer.SourceAddress.Address != 0)
                    {
                        DHCPIP = packetIpLayer.SourceAddress;
                    }
                    //We get the DHCP Server MAC
                    if (mtype->type == DHCP.DHCPOFFER)
                    {
                        DHCPMAC = (p as EthernetPacket).SourceHwAddress;
                    }
                    //We only continue if it's a DHCP Request
                    if (mtype->type != DHCP.DHCPREQUEST)
                    {
                        return;
                    }
                    break;
                }

                case DHCP.TAG_REQUESTED_IP:
                {
                    optionRequestedIP.id    = ((DHCP.RequestedIP *)(dhcp->bp_vend + pos))->id;
                    existsOptionRequestedIP = true;
                    break;
                }

                case DHCP.TAG_SERVER_ID:
                {
                    optionServerID.id    = ((DHCP.ServerID *)(dhcp->bp_vend + pos))->id;
                    DHCPIP               = new IPAddress(optionServerID.id);
                    existsOptionServerID = true;
                    break;
                }

                case DHCP.TAG_HOSTNAME:
                {
                    byte *chr    = (((DHCP.Hostname *)(dhcp->bp_vend + pos))->name);
                    byte  lenght = ((DHCP.Hostname *)(dhcp->bp_vend + pos))->optionHeader.lenght;
                    for (int i = 0; i < lenght; i++)
                    {
                        Strname += (char)chr[i];
                    }
                    break;
                }
                }
                pos += (uint)len + 2; //The option and the length field
            }

            bool   realizarataque = false;
            string dns            = string.Empty;
            string gateway        = string.Empty;
            string MAC;

            foreach (Data.Attack attack in attacks.Where(A => A.attackType == Data.AttackType.DHCPACKInjection && A.attackStatus == Data.AttackStatus.Attacking))
            {
                dns     = (attack as DHCPACKInjectionAttack).dns;
                gateway = (attack as DHCPACKInjectionAttack).gateway;
                MAC     = (attack as DHCPACKInjectionAttack).MAC;
                //If filter does not apply not continue
                if (!string.IsNullOrEmpty(MAC) && !(p.PayloadPacket as EthernetPacket).SourceHwAddress.Equals(PhysicalAddress.Parse(MAC)))
                {
                    realizarataque = false;
                }
                else
                {
                    realizarataque = true;
                    break;
                }
            }
            if (!realizarataque)
            {
                return;
            }

            //Configuration used in the attack
            PhysicalAddress MACUsed;

            if (Program.CurrentProject.data.settings.UseRealDHCPData)
            {
                if (DHCPMAC != null)
                {
                    MACUsed = DHCPMAC;
                }
                else //If the real dhcp server mac is not found we use the computer network device mac
                {
                    MACUsed = device.Interface.MacAddress;
                }
            }
            else
            {
                MACUsed = PhysicalAddress.Parse(Program.CurrentProject.data.settings.DHCPFakeServerMAC);
            }

            IPAddress IPUsed;

            if (Program.CurrentProject.data.settings.UseRealDHCPData)
            {
                if (existsOptionServerID)
                {
                    IPUsed = new IPAddress(optionServerID.id);
                }
                else
                {
                    if (DHCPIP.Address == 0)
                    {
                        Program.LogThis("DHCP IP Address unknown, using 0.0.0.0 as IP source", Logs.Log.LogType.DHCPACKInjection);
                        IPUsed = IPAddress.Parse("0.0.0.0");
                    }
                    else
                    {
                        IPUsed = DHCPIP;
                    }
                }
            }
            else
            {
                IPUsed = IPAddress.Parse(Program.CurrentProject.data.settings.DHCPFakeServerIP);
            }

            //Now we create a fake response
            EthernetPacket response = new EthernetPacket(MACUsed, new PhysicalAddress(new byte[] { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }), EthernetPacketType.IpV4);

            response.PayloadPacket = new IPv4Packet(IPUsed, new System.Net.IPAddress(0xffffffff));

            //We want to follow the IP communication
            (response.PayloadPacket as IPv4Packet).Id = packetIpLayer.Id;

            response.PayloadPacket.PayloadPacket             = new UdpPacket(67, 68);
            response.PayloadPacket.PayloadPacket.PayloadData = new byte[16];
            response.PayloadPacket.PayloadPacket.PayloadData = new byte[sizeof(DHCP.bootp) + sizeof(DHCP.optionsResponse)];

            dhcp->bp_op = DHCP.BOOTPREPLY;
            if (existsOptionRequestedIP)
            {
                dhcp->bp_yiaddr = optionRequestedIP.id;
            }
            else if (dhcp->bp_ciaddr != 0)
            {
                dhcp->bp_yiaddr = dhcp->bp_ciaddr;
            }
            else
            {
                return;
            }

            dhcp->bp_flags = 0;
            Marshal.Copy(new IntPtr(dhcp), response.PayloadPacket.PayloadPacket.PayloadData, 0, sizeof(DHCP.bootp));

            //We need to fill the optionResponseStatic fields
            if (existsOptionServerID)
            {
                optionResponseStatic.serverID.id = optionServerID.id;
            }
            optionResponseStatic.serverID.id         = (uint)IPUsed.Address;
            optionResponseStatic.route.ip            = (uint)IPAddress.Parse(gateway).Address;
            optionResponseStatic.domainNameServer.ip = (uint)IPAddress.Parse(dns).Address;

            fixed(DHCP.optionsResponse *op = &optionResponseStatic)
            {
                Marshal.Copy(new IntPtr(op), response.PayloadPacket.PayloadPacket.PayloadData, sizeof(DHCP.bootp), sizeof(DHCP.optionsResponse));
            }

            response.UpdateCalculatedValues();
            (response.PayloadPacket as IPv4Packet).UpdateCalculatedValues();
            (response.PayloadPacket as IPv4Packet).UpdateIPChecksum();
            (response.PayloadPacket.PayloadPacket as UdpPacket).UpdateCalculatedValues();
            (response.PayloadPacket.PayloadPacket as UdpPacket).UpdateUDPChecksum();

            device.SendPacket(response);
            string message = string.Format("DHCP ACK sent to a {0} DHCP Request", new IPAddress(dhcp->bp_yiaddr).ToString());

            Program.LogThis(message, Logs.Log.LogType.DHCPACKInjection);
        }
Esempio n. 20
0
        public static Loadout MakeBuild(Monster mon, Rune[][] runesSlot, Func <Stats, double> sort, Predicate <RuneSet[]> reqsets = null, Predicate <Stats> minimum = null)
        {
            SynchronizedCollection <Monster> tests = new SynchronizedCollection <Monster>();//new List<Monster>();
            long count = 0;
            long total = runesSlot[0].Count();

            total *= runesSlot[1].Count();
            total *= runesSlot[2].Count();
            total *= runesSlot[3].Count();
            total *= runesSlot[4].Count();
            total *= runesSlot[5].Count();
            long complete = total;

            DateTime timer = DateTime.Now;

            Console.WriteLine(count + "/" + total + "  " + String.Format("{0:P2}", ((count + complete - total) / (double)complete)));

            Parallel.ForEach(runesSlot[0], r0 =>
            {
                int kill = 0;
                int plus = 0;

                foreach (Rune r1 in runesSlot[1])
                {
                    foreach (Rune r2 in runesSlot[2])
                    {
                        foreach (Rune r3 in runesSlot[3])
                        {
                            foreach (Rune r4 in runesSlot[4])
                            {
                                foreach (Rune r5 in runesSlot[5])
                                {
                                    Monster test = new Monster(mon);
                                    test.ApplyRune(r0);
                                    test.ApplyRune(r1);
                                    test.ApplyRune(r2);
                                    test.ApplyRune(r3);
                                    test.ApplyRune(r4);
                                    test.ApplyRune(r5);

                                    if (minimum != null && !minimum.Invoke(test.GetStats()))
                                    {
                                        kill++;
                                    }
                                    else if (reqsets != null && !reqsets.Invoke(test.Current.Sets))
                                    {
                                        kill++;
                                    }
                                    else
                                    {
                                        plus++;
                                        tests.Add(test);
                                    }


                                    if (DateTime.Now > timer.AddSeconds(1))
                                    {
                                        timer = DateTime.Now;
                                        Console.WriteLine(count + "/" + total + "  " + String.Format("{0:P2}", (count + complete - total) / (double)complete));
                                    }
                                }
                                Interlocked.Add(ref total, -kill);
                                kill = 0;
                                Interlocked.Add(ref count, plus);
                                plus = 0;
                            }
                        }
                    }
                }
            });
            Console.WriteLine(count + "/" + total + "  " + String.Format("{0:P2}", (count + complete - total) / (double)complete));

            var desc = tests.Where(t => t != null).OrderByDescending(r => sort(r.GetStats())).Take(10).ToArray();

            foreach (var l in desc)
            {
                Console.WriteLine(l.GetStats().Health + "  " + l.GetStats().Attack + "  " + l.GetStats().Defense + "  " + l.GetStats().Speed
                                  + "  " + l.GetStats().CritRate + "%" + "  " + l.GetStats().CritDamage + "%" + "  " + l.GetStats().Resistance + "%" + "  " + l.GetStats().Accuracy + "%");
            }

            if (!desc.Any())
            {
                Console.WriteLine("No builds :(");
                return(null);
            }

            var best = desc.First().Current;

            foreach (Rune r in best.Runes)
            {
                r.Locked = true;
            }

            return(best);
        }
 public int CountClientsWithSameIP(Socket socket)
 {
     return(Clients.Where(x => x.IP == socket.RemoteEndPoint.AddressFamily.ToString()).Count());
 }
Esempio n. 22
0
        public static Loadout MakeBuild(Monster mon, IEnumerable<Rune>[] runesSlot, Func<Stats, double> sort, Predicate<RuneSet[]> reqsets = null, Predicate<Stats> minimum = null)
        {
            System.Collections.Generic.SynchronizedCollection<Monster> tests = new SynchronizedCollection<Monster>();//new List<Monster>();
            long count = 0;
            long total = runesSlot[0].Count();
            total *= runesSlot[1].Count();
            total *= runesSlot[2].Count();
            total *= runesSlot[3].Count();
            total *= runesSlot[4].Count();
            total *= runesSlot[5].Count();
            long complete = total;

            DateTime timer = DateTime.Now;

            Console.WriteLine(count + "/" + total + "  " + String.Format("{0:P2}", (double)(count + complete - total) / (double)complete));

            Parallel.ForEach<Rune>(runesSlot[0], r0 =>
            {
                int kill = 0;
                int plus = 0;

                foreach (Rune r1 in runesSlot[1])
                {
                    foreach (Rune r2 in runesSlot[2])
                    {
                        foreach (Rune r3 in runesSlot[3])
                        {
                            foreach (Rune r4 in runesSlot[4])
                            {
                                foreach (Rune r5 in runesSlot[5])
                                {
                                    Monster test = new Monster(mon);
                                    test.ApplyRune(r0);
                                    test.ApplyRune(r1);
                                    test.ApplyRune(r2);
                                    test.ApplyRune(r3);
                                    test.ApplyRune(r4);
                                    test.ApplyRune(r5);

                                    if (minimum != null && !minimum.Invoke(test.GetStats()))
                                    {
                                        //total--;
                                        kill++;
                                        //Interlocked.Decrement(ref total);
                                    }
                                    else if (reqsets != null && !reqsets.Invoke(test.Current.sets))
                                    {
                                        kill++;
                                        //Interlocked.Decrement(ref total);
                                    }
                                    else
                                    {
                                        plus++;
                                        tests.Add(test);
                                        //Interlocked.Increment(ref count);
                                        //count++;
                                    }

                                    if (DateTime.Now > timer.AddSeconds(1))
                                    {
                                        timer = DateTime.Now;
                                        Console.WriteLine(count + "/" + total + "  " + String.Format("{0:P2}", (double)(count + complete - total) / (double)complete));
                                    }
                                }
                                Interlocked.Add(ref total, -kill);
                                kill = 0;
                                Interlocked.Add(ref count, plus);
                                plus = 0;
                            }
                        }
                    }
                }
            });
            Console.WriteLine(count + "/" + total + "  " + String.Format("{0:P2}", (double)(count + complete - total) / (double)complete));

            var desc = tests.Where(t => t != null).OrderByDescending(r => sort(r.GetStats())).Take(10).ToArray();
            foreach (var l in desc)
            {
                Console.WriteLine(l.GetStats().Health + "  " + l.GetStats().Attack + "  " + l.GetStats().Defense + "  " + l.GetStats().Speed
                    + "  " + l.GetStats().CritRate + "%" + "  " + l.GetStats().CritDamage + "%" + "  " + l.GetStats().Resistance + "%" + "  " + l.GetStats().Accuracy + "%");
            }

            if (desc.Count() == 0)
            {
                Console.WriteLine("No builds :(");
                return null;
            }

            var best = desc.First().Current;

            foreach (Rune r in best.runes)
            {
                r.Locked = true;
            }

            return best;
        }
Esempio n. 23
0
 public SynchronizedCollection <Port> GetPorts(IPAddress ip)
 {
     return(new SynchronizedCollection <Port>(ports.Where(P => P.ip.Equals(ip)).ToList()));
 }
Esempio n. 24
0
        public void AnalyzePacket(Packet p)
        {
            try
            {
                if (p is EthernetPacket)
                {
                    if (p.PayloadPacket == null)
                    {
                        return;
                    }

                    //Para que no se procesen los paquetes del DoS
                    if ((p as EthernetPacket).SourceHwAddress.Equals(DoSSLAAC.MACsrc))
                    {
                        return;
                    }

                    if (p.PayloadPacket is ARPPacket)
                    {
                        AnalyzeARP(p);
                    }

                    if (p.PayloadPacket is IPv6Packet)
                    {
                        AnalyzeIPv6Packet(p);
                    }
                    else if (p.PayloadPacket is IPv4Packet)
                    {
                        AnalyzeIPv4Packet(p);
                    }
                    AnalyzeLLMNR(p);

                    // Ataque pasivo DHCP ACK Injector en Ipv4

                    if ((attacks.Where(A => A.attackType == AttackType.DHCPACKInjection && A.attackStatus == AttackStatus.Attacking).Count() > 0))
                    {
                        if (DHCPACKInjection.CheckIfIsDHCP(p))
                        {
                            DHCPACKInjection.AnalyzePacket(device, p);
                        }
                    }

                    // Ataque pasivo DHCP IPv6
                    if ((attacks.Where(A => A.attackType == AttackType.DHCPIpv6 && A.attackStatus == AttackStatus.Attacking).Count() > 0))
                    {
                        if (DHCPIpv6.CheckIfIsRequestDHCPIpv6(p))
                        {
                            DHCPIpv6.AnalyzePacket(device, p);
                        }
                    }

                    OSDetector.AnalyzePacket(p);
                    pasivePortScan.AnalyzePacket(p);

                    route.CheckToRoutePacket(p);
                }
            }
            catch
            {
                // Paquete perdido!!!
            }
        }
Esempio n. 25
0
        private void AnalyzeIPv6Packet(Packet packet)
        {
            if (!(packet.PayloadPacket is IPv6Packet))
            {
                return;
            }
            if (!(packet is EthernetPacket))
            {
                return;
            }

            PhysicalAddress macSrc = ((EthernetPacket)packet).SourceHwAddress;
            PhysicalAddress macDst = ((EthernetPacket)packet).DestinationHwAddress;
            IPAddress       ipSrc  = ((IPv6Packet)(((EthernetPacket)packet).PayloadPacket)).SourceAddress;
            IPAddress       ipDst  = ((IPv6Packet)(((EthernetPacket)packet).PayloadPacket)).DestinationAddress;

            Data.Neighbor neighborSrc = new Data.Neighbor();
            Data.Neighbor neighborDst = new Data.Neighbor();

            neighborSrc.physicalAddress = macSrc;
            neighborSrc.AddIP(ipSrc);
            neighborDst.physicalAddress = macDst;
            neighborDst.AddIP(ipDst);

            if ((ipSrc.IsIPv6LinkLocal) && (ipDst.IsIPv6LinkLocal || ipDst.IsIPv6Multicast) && (packet.PayloadPacket.PayloadPacket is ICMPv6Packet))
            {
                AnalyzeICMPv6Packet(packet);
            }

            if (ipSrc.IsIPv6LinkLocal)
            {
                // [ Si no se envia desde nuestra mac ] Y [ el vecino no existe ] -> Se crea el vecino
                if (!macSrc.Equals(localPhysicalAddress) && !Program.CurrentProject.data.ExistsNeighbor(macSrc))
                {
                    Program.CurrentProject.data.AddNeighbor(neighborSrc);
                    OnNewNeighbor(new NeighborEventArgs(neighborSrc));
                }
                // En caso de que el vecino (mac) tenga una nueva IP, se la añadimos
                if (Program.CurrentProject.data.GetNeighbor(neighborSrc.physicalAddress) != null &&
                    !Program.CurrentProject.data.GetNeighbor(neighborSrc.physicalAddress).ExistsIP(ipSrc))
                {
                    Program.CurrentProject.data.GetNeighbor(neighborSrc.physicalAddress).AddIP(ipSrc);
                    Program.CurrentProject.data.AddNeighbor(neighborSrc);
                }
            }

            if (ipDst.IsIPv6LinkLocal)
            {
                // [ Si el destino no es nuestra mac ] Y [ el vecino no existe ] -> Se crea el vecino
                if (!macDst.Equals(localPhysicalAddress) && !Program.CurrentProject.data.ExistsNeighbor(macDst))
                {
                    Program.CurrentProject.data.AddNeighbor(neighborDst);
                    OnNewNeighbor(new NeighborEventArgs(neighborDst));
                }
                if (Program.CurrentProject.data.GetNeighbor(neighborDst.physicalAddress) != null &&
                    !Program.CurrentProject.data.GetNeighbor(neighborDst.physicalAddress).ExistsIP(ipDst))
                {
                    Program.CurrentProject.data.GetNeighbor(neighborDst.physicalAddress).AddIP(ipDst);
                    Program.CurrentProject.data.AddNeighbor(neighborDst);
                }
            }

            if ((packet.PayloadPacket.PayloadPacket is TcpPacket) &&
                (((TcpPacket)(packet.PayloadPacket.PayloadPacket)).DestinationPort == 80) &&
                (((EthernetPacket)packet).Type == EthernetPacketType.IpV6) &&
                ((IPv6Packet)(((EthernetPacket)packet).PayloadPacket)).DestinationAddress.Equals(Program.CurrentProject.data.GetIPv6LocalLinkFromDevice(device)))
            {
                SynchronizedCollection <Attack> lstAttacks = Program.CurrentProject.data.GetAttacks();

                foreach (Attack attk in lstAttacks.Where(A => A.attackType == AttackType.WpadIPv6 && A.attackStatus == AttackStatus.Attacking))
                {
                    MitmAttack mitmAtt = (MitmAttack)attk;
                    if (((IPv6Packet)((EthernetPacket)packet).PayloadPacket).SourceAddress.Equals(mitmAtt.t2.ip))
                    {
                        WpadIPv6Attack.Instance.SendWpadFile(packet);
                    }
                }
            }
        }
Esempio n. 26
0
        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;
                        }
                    }
                });
            }
        }
Esempio n. 27
0
        public T FirstOrDefault <T>(Func <T, bool> predicate)
        {
            var list = m_CachedList.Where(i => i.Value.GetType() == typeof(T)).Select(i => i.Value).Cast <T>();

            return(list.FirstOrDefault(predicate));
        }
Esempio n. 28
0
        /// <summary>
        /// Generates builds based on the instances variables.
        /// </summary>
        /// <param name="top">If non-zero, runs until N builds are generated</param>
        /// <param name="time">If non-zero, runs for N seconds</param>
        /// <param name="printTo">Periodically gives progress% and if it failed</param>
        /// <param name="progTo">Periodically gives the progress% as a double</param>
        /// <param name="dumpBads">If true, will only track new builds if they score higher than an other found builds</param>
        public void GenBuilds(int top = 0, int time = 0, Action <string> printTo = null, Action <double> progTo = null, bool dumpBads = false, bool saveStats = false)
        {
            if (runes.Any(r => r == null))
            {
                return;
            }
            try
            {
                Best = null;
                SynchronizedCollection <Monster> tests = new SynchronizedCollection <Monster>();
                long count = 0;
                long total = runes[0].Count();
                total *= runes[1].Count();
                total *= runes[2].Count();
                total *= runes[3].Count();
                total *= runes[4].Count();
                total *= runes[5].Count();
                long complete = total;

                if (total == 0)
                {
                    if (printTo != null)
                    {
                        printTo.Invoke("0 perms");
                    }
                    Console.WriteLine("Zero permuations");
                    return;
                }
                if (!AllowBroken && BuildSets.Count == 1 && Rune.SetRequired(BuildSets[0]) == 4)
                {
                    if (printTo != null)
                    {
                        printTo.Invoke("Bad sets");
                    }
                    Console.WriteLine("Cannot use 4 set with no broken");
                    return;
                }

                bool hasSort = false;
                foreach (string stat in statNames)
                {
                    if (Sort[stat] != 0)
                    {
                        hasSort = true;
                        break;
                    }
                }
                foreach (string extra in extraNames)
                {
                    if (Sort.ExtraGet(extra) != 0)
                    {
                        hasSort = true;
                        break;
                    }
                }
                if (top == 0 && !hasSort)
                {
                    if (printTo != null)
                    {
                        printTo.Invoke("No sort");
                    }
                    Console.WriteLine("No method of determining best");
                    return;
                }

                DateTime begin = DateTime.Now;
                DateTime timer = DateTime.Now;

                Console.WriteLine(count + "/" + total + "  " + string.Format("{0:P2}", (count + complete - total) / (double)complete));

                // build the scoring function
                Func <Stats, double> sort = (m) =>
                {
                    double pts = 0;

                    foreach (string stat in statNames)
                    {
                        // if this stat is used for sorting
                        if (Sort[stat] != 0)
                        {
                            // sum points for the stat
                            pts += m[stat] / Sort[stat];
                            // if exceeding max, subtracted the gained points and then some
                            if (Threshold[stat] != 0)
                            {
                                pts -= Math.Max(0, m[stat] - Threshold[stat]) / Sort[stat];
                            }
                        }
                    }
                    // look, cool metrics!
                    foreach (string extra in extraNames)
                    {
                        if (Sort.ExtraGet(extra) != 0)
                        {
                            pts += m.ExtraValue(extra) / Sort.ExtraGet(extra);
                            if (Threshold.ExtraGet(extra) != 0)
                            {
                                pts -= Math.Max(0, m.ExtraValue(extra) - Threshold.ExtraGet(extra)) / Sort.ExtraGet(extra);
                            }
                        }
                    }

                    return(pts);
                };

                int[]  slotFakes = new int[6];
                bool[] slotPred  = new bool[6];

                // crank the rune prediction
                for (int i = 0; i < 6; i++)
                {
                    Rune[] rs          = runes[i];
                    int    raiseTo     = 0;
                    bool   predictSubs = false;

                    // find the largest number to raise to
                    // if any along the tree say to predict, do it
                    if (runePrediction.ContainsKey("g"))
                    {
                        int glevel = runePrediction["g"].Key;
                        if (glevel > raiseTo)
                        {
                            raiseTo = glevel;
                        }
                        predictSubs |= runePrediction["g"].Value;
                    }
                    if (runePrediction.ContainsKey(((i % 2 == 0) ? "o" : "e")))
                    {
                        int mlevel = runePrediction[((i % 2 == 0) ? "o" : "e")].Key;
                        if (mlevel > raiseTo)
                        {
                            raiseTo = mlevel;
                        }
                        predictSubs |= runePrediction[((i % 2 == 0) ? "o" : "e")].Value;
                    }
                    if (runePrediction.ContainsKey((i + 1).ToString()))
                    {
                        int slevel = runePrediction[(i + 1).ToString()].Key;
                        if (slevel > raiseTo)
                        {
                            raiseTo = slevel;
                        }
                        predictSubs |= runePrediction[(i + 1).ToString()].Value;
                    }

                    slotFakes[i] = raiseTo;
                    slotPred[i]  = predictSubs;
                }

                // set to running
                isRun = true;

                // Parallel the outer loop
                var loopRes = Parallel.ForEach <Rune>(runes[0], (r0, loopState) =>
                {
                    if (!isRun)
                    {
                        //break;
                        loopState.Break();
                    }

                    // number of builds ruled out since last sync
                    int kill = 0;
                    // number of builds added since last sync
                    int plus = 0;

                    foreach (Rune r1 in runes[1])
                    {
                        if (!isRun) // Can't break to a lable, don't want to goto
                        {
                            break;
                        }
                        foreach (Rune r2 in runes[2])
                        {
                            if (!isRun)
                            {
                                break;
                            }
                            foreach (Rune r3 in runes[3])
                            {
                                if (!isRun)
                                {
                                    break;
                                }
                                foreach (Rune r4 in runes[4])
                                {
                                    if (!isRun)
                                    {
                                        break;
                                    }
                                    foreach (Rune r5 in runes[5])
                                    {
                                        if (!isRun)
                                        {
                                            break;
                                        }

                                        Monster test         = new Monster(mon);
                                        test.Current.shrines = shrines;
                                        test.Current.leader  = leader;

                                        test.Current.FakeLevel   = slotFakes;
                                        test.Current.PredictSubs = slotPred;

                                        test.ApplyRune(r0);
                                        test.ApplyRune(r1);
                                        test.ApplyRune(r2);
                                        test.ApplyRune(r3);
                                        test.ApplyRune(r4);
                                        test.ApplyRune(r5);

                                        if (saveStats)
                                        {
                                            foreach (Rune r in test.Current.runes)
                                            {
                                                r.manageStats_LoadGen++;
                                            }
                                        }

                                        var cstats = test.GetStats();

                                        bool maxdead = false;

                                        if (Maximum != null)
                                        {
                                            foreach (var stat in statNames)
                                            {
                                                if (Maximum[stat] > 0 && cstats[stat] > Maximum[stat])
                                                {
                                                    maxdead = true;
                                                    break;
                                                }
                                            }
                                        }

                                        // check if build meets minimum
                                        if (Minimum != null && !(cstats > Minimum))
                                        {
                                            kill++;
                                        }
                                        else if (maxdead)
                                        {
                                            kill++;
                                        }
                                        // if no broken sets, check for broken sets
                                        else if (!AllowBroken && !test.Current.SetsFull)
                                        {
                                            kill++;
                                        }
                                        // if there are required sets, ensure we have them
                                        else if (RequiredSets != null && RequiredSets.Count > 0 && !RequiredSets.All(s => test.Current.sets.Contains(s)))
                                        {
                                            kill++;
                                        }
                                        else
                                        {
                                            // we found an okay build!
                                            plus++;

                                            if (saveStats)
                                            {
                                                foreach (Rune r in test.Current.runes)
                                                {
                                                    r.manageStats_LoadFilt++;
                                                }
                                            }

                                            // if we are to track all good builds, keep it
                                            if (!dumpBads)
                                            {
                                                tests.Add(test);
                                            }
                                            else
                                            {
                                                //lock (tests)
                                                //{
                                                // if there are currently no good builds, keep it

                                                if (tests.FirstOrDefault() == null)
                                                {
                                                    tests.Add(test);
                                                    Best = test;
                                                }
                                                else
                                                {
                                                    if (Best.GetStats() < test.GetStats())
                                                    {
                                                        Best = test;
                                                        tests.Add(test);
                                                    }

                                                    // take a snapshot of the builds (multithread /may/ cause a "collection modified" excepion in next step)

                                                    /*var tt = tests.ToList();
                                                     * // if this build is better than any other build, keep it
                                                     * // can't just keep a copy of Max becaues of threading
                                                     * if (tt.Max(t => sort(t.GetStats())) < sort(test.GetStats()))
                                                     * {
                                                     *  tests.Add(test);
                                                     * }*/
                                                }
                                                //}
                                            }
                                        }

                                        // every second, give a bit of feedback to those watching
                                        if (DateTime.Now > timer.AddSeconds(1))
                                        {
                                            timer = DateTime.Now;
                                            Console.WriteLine(count + "/" + total + "  " + String.Format("{0:P2}", (double)(count + complete - total) / (double)complete));
                                            if (printTo != null)
                                            {
                                                printTo.Invoke(String.Format("{0:P2}", (double)(count + complete - total) / (double)complete));
                                            }
                                            if (progTo != null)
                                            {
                                                progTo.Invoke((double)(count + complete - total) / (double)complete);
                                            }

                                            if (time > 0)
                                            {
                                                if (DateTime.Now > begin.AddSeconds(time))
                                                {
                                                    isRun = false;
                                                    break;
                                                }
                                            }
                                        }
                                    }
                                    // sum up what work we've done
                                    Interlocked.Add(ref total, -kill);
                                    kill = 0;
                                    Interlocked.Add(ref count, plus);
                                    plus = 0;

                                    // if we've got enough, stop
                                    if (top > 0 && count >= top)
                                    {
                                        isRun = false;
                                        break;
                                    }
                                }
                            }
                        }
                    }
                });

                // write out completion
                Console.WriteLine(isRun + " " + count + "/" + total + "  " + String.Format("{0:P2}", (double)(count + complete - total) / (double)complete));
                if (printTo != null)
                {
                    printTo.Invoke("100%");
                }
                if (progTo != null)
                {
                    progTo.Invoke(1);
                }

                // sort *all* the builds
                loads = tests.Where(t => t != null).OrderByDescending(r => sort(r.GetStats())).Take((top > 0 ? top : 1));

                // dump everything to console, if nothing to print to
                if (printTo == null)
                {
                    foreach (var l in loads)
                    {
                        Console.WriteLine(l.GetStats().Health + "  " + l.GetStats().Attack + "  " + l.GetStats().Defense + "  " + l.GetStats().Speed
                                          + "  " + l.GetStats().CritRate + "%" + "  " + l.GetStats().CritDamage + "%" + "  " + l.GetStats().Resistance + "%" + "  " + l.GetStats().Accuracy + "%");
                    }
                }

                // sadface if no builds
                if (loads.Count() == 0)
                {
                    Console.WriteLine("No builds :(");
                    if (printTo != null)
                    {
                        printTo.Invoke("Zero :(");
                    }
                }
                else
                {
                    // remember the good one
                    Best = loads.First();
                    foreach (Rune r in Best.Current.runes)
                    {
                        r.manageStats_In = true;
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Error " + e);
                if (printTo != null)
                {
                    printTo.Invoke(e.ToString());
                }
            }
        }
Esempio n. 29
0
        /// <summary>
        /// Generates builds based on the instances variables.
        /// </summary>
        /// <param name="top">If non-zero, runs until N builds are generated</param>
        /// <param name="time">If non-zero, runs for N seconds</param>
        /// <param name="printTo">Periodically gives progress% and if it failed</param>
        /// <param name="progTo">Periodically gives the progress% as a double</param>
        /// <param name="dumpBads">If true, will only track new builds if they score higher than an other found builds</param>
        public void GenBuilds(int top = 0, int time = 0, Action<string> printTo = null, Action<double> progTo = null, bool dumpBads = false, bool saveStats = false)
        {
            if (runes.Any(r => r == null))
                return;

            // if to get awakened
            if (DownloadAwake && !mon.downloaded)
            {
                var mref = MonsterStat.FindMon(mon);
                if (mref != null)
                {
                    // download the current (unawakened monster)
                    var mstat = mref.Download();
                    // if the retrieved mon is unawakened, get the awakened
                    if (!mstat.Awakened && mstat.AwakenRef != null)
                    {
                        mon = mstat.AwakenRef.Download().GetMon(mon);
                    }
                }
            }
            // getting awakened also gets level 40, so...
            // only get lvl 40 stats if the monster isn't 40, wants to download AND isn't already downloaded (first and last are about the same)
            else if (mon.level < 40 && DownloadStats && !mon.downloaded)
            {
                var mref = MonsterStat.FindMon(mon);
                if (mref != null)
                {
                    mon = mref.Download().GetMon(mon);
                }
            }

            try
            {
                Best = null;
                SynchronizedCollection<Monster> tests = new SynchronizedCollection<Monster>();
                long count = 0;
                long total = runes[0].Count();
                total *= runes[1].Count();
                total *= runes[2].Count();
                total *= runes[3].Count();
                total *= runes[4].Count();
                total *= runes[5].Count();
                long complete = total;

                if (total == 0)
                {
                    if (printTo != null)
                        printTo.Invoke("0 perms");
                    Console.WriteLine("Zero permuations");
                    return;
                }
                if (!AllowBroken && BuildSets.Count == 1 && Rune.SetRequired(BuildSets[0]) == 4)
                {
                    if (printTo != null)
                        printTo.Invoke("Bad sets");
                    Console.WriteLine("Cannot use 4 set with no broken");
                    return;
                }

                bool hasSort = false;
                foreach (string stat in statNames)
                {
                    if (Sort[stat] != 0)
                    {
                        hasSort = true;
                        break;
                    }
                }
                foreach (string extra in extraNames)
                {
                    if (Sort.ExtraGet(extra) != 0)
                    {
                        hasSort = true;
                        break;
                    }
                }
                if (top == 0 && !hasSort)
                {
                    if (printTo != null)
                        printTo.Invoke("No sort");
                    Console.WriteLine("No method of determining best");
                    return;
                }

                DateTime begin = DateTime.Now;
                DateTime timer = DateTime.Now;

                Console.WriteLine(count + "/" + total + "  " + string.Format("{0:P2}", (count + complete - total) / (double)complete));

                // build the scoring function
                Func<Stats, double> sort = (m) =>
                {
                    double pts = 0;

                    foreach (string stat in statNames)
                    {
                    // if this stat is used for sorting
                    if (Sort[stat] != 0)
                        {
                        // sum points for the stat
                        pts += m[stat] / Sort[stat];
                        // if exceeding max, subtracted the gained points and then some
                        if (Threshold[stat] != 0)
                                pts -= Math.Max(0, m[stat] - Threshold[stat]) / Sort[stat];
                        }
                    }
                    // look, cool metrics!
                    foreach (string extra in extraNames)
                    {
                        if (Sort.ExtraGet(extra) != 0)
                        {
                            pts += m.ExtraValue(extra) / Sort.ExtraGet(extra);
                            if (Threshold.ExtraGet(extra) != 0)
                                pts -= Math.Max(0, m.ExtraValue(extra) - Threshold.ExtraGet(extra)) / Sort.ExtraGet(extra);
                        }
                    }
                    return pts;
                };

                int[] slotFakes = new int[6];
                bool[] slotPred = new bool[6];

                // crank the rune prediction
                for (int i = 0; i < 6; i++)
                {
                    Rune[] rs = runes[i];
                    int raiseTo = 0;
                    bool predictSubs = false;

                    // find the largest number to raise to
                    // if any along the tree say to predict, do it
                    if (runePrediction.ContainsKey("g"))
                    {
                        int glevel = runePrediction["g"].Key;
                        if (glevel > raiseTo)
                            raiseTo = glevel;
                        predictSubs |= runePrediction["g"].Value;
                    }
                    if (runePrediction.ContainsKey(((i % 2 == 0) ? "o" : "e")))
                    {
                        int mlevel = runePrediction[((i % 2 == 0) ? "o" : "e")].Key;
                        if (mlevel > raiseTo)
                            raiseTo = mlevel;
                        predictSubs |= runePrediction[((i % 2 == 0) ? "o" : "e")].Value;
                    }
                    if (runePrediction.ContainsKey((i + 1).ToString()))
                    {
                        int slevel = runePrediction[(i + 1).ToString()].Key;
                        if (slevel > raiseTo)
                            raiseTo = slevel;
                        predictSubs |= runePrediction[(i + 1).ToString()].Value;
                    }

                    slotFakes[i] = raiseTo;
                    slotPred[i] = predictSubs;

                }

                // set to running
                isRun = true;

                // Parallel the outer loop
                var loopRes = Parallel.ForEach<Rune>(runes[0], (r0, loopState) =>
                {
                    if (!isRun)
                    //break;
                    loopState.Break();

                // number of builds ruled out since last sync
                int kill = 0;
                // number of builds added since last sync
                int plus = 0;

                    foreach (Rune r1 in runes[1])
                    {
                        if (!isRun) // Can't break to a lable, don't want to goto
                        break;
                        foreach (Rune r2 in runes[2])
                        {
                            if (!isRun)
                                break;
                            foreach (Rune r3 in runes[3])
                            {
                                if (!isRun)
                                    break;
                                foreach (Rune r4 in runes[4])
                                {
                                    if (!isRun)
                                        break;
                                    foreach (Rune r5 in runes[5])
                                    {
                                        if (!isRun)
                                            break;

                                        Monster test = new Monster(mon);
                                        test.Current.shrines = shrines;
                                        test.Current.leader = leader;

                                        test.Current.FakeLevel = slotFakes;
                                        test.Current.PredictSubs = slotPred;

                                        test.ApplyRune(r0);
                                        test.ApplyRune(r1);
                                        test.ApplyRune(r2);
                                        test.ApplyRune(r3);
                                        test.ApplyRune(r4);
                                        test.ApplyRune(r5);

                                        if (saveStats)
                                        {
                                            foreach (Rune r in test.Current.runes)
                                            {
                                                r.manageStats_LoadGen++;
                                            }
                                        }

                                        var cstats = test.GetStats();

                                        bool maxdead = false;

                                        if (Maximum != null)
                                        {
                                            foreach (var stat in statNames)
                                            {
                                                if (Maximum[stat] > 0 && cstats[stat] > Maximum[stat])
                                                {
                                                    maxdead = true;
                                                    break;
                                                }
                                            }
                                        }

                                        // check if build meets minimum
                                        if (Minimum != null && !(cstats > Minimum))
                                        {
                                            kill++;
                                        }
                                        else if (maxdead)
                                        {
                                            kill++;
                                        }
                                        // if no broken sets, check for broken sets
                                        else if (!AllowBroken && !test.Current.SetsFull)
                                        {
                                            kill++;
                                        }
                                        // if there are required sets, ensure we have them
                                        else if (RequiredSets != null && RequiredSets.Count > 0
                                        // this Linq adds no overhead compared to GetStats() and ApplyRune()
                                            && !RequiredSets.All(s => test.Current.sets.Count(q => q == s) >= RequiredSets.Count(q => q == s)))
                                        {
                                            kill++;
                                        }
                                        else
                                        {
                                            // we found an okay build!
                                            plus++;

                                            if (saveStats)
                                            {
                                                foreach (Rune r in test.Current.runes)
                                                {
                                                    r.manageStats_LoadFilt++;
                                                }
                                            }

                                            // if we are to track all good builds, keep it
                                            if (!dumpBads)
                                            {
                                                tests.Add(test);
                                            }
                                            // if we only want to track really good builds
                                            else
                                            {
                                                // if there are currently no good builds, keep it
                                                if (tests.FirstOrDefault() == null)
                                                {
                                                    tests.Add(test);
                                                    Best = test;
                                                }
                                                else
                                                {
                                                    // if this build is better than the best, keep it
                                                    if (sort(Best.GetStats()) < sort(test.GetStats()))
                                                    {
                                                        Best = test;
                                                        tests.Add(test);
                                                    }
                                                }
                                            }
                                        }

                                        // every second, give a bit of feedback to those watching
                                        if (DateTime.Now > timer.AddSeconds(1))
                                        {
                                            timer = DateTime.Now;
                                            Console.WriteLine(count + "/" + total + "  " + String.Format("{0:P2}", (double)(count + complete - total) / (double)complete));
                                            if (printTo != null)
                                                printTo.Invoke(String.Format("{0:P2}", (double)(count + complete - total) / (double)complete));
                                            if (progTo != null)
                                                progTo.Invoke((double)(count + complete - total) / (double)complete);

                                            if (time > 0)
                                            {
                                                if (DateTime.Now > begin.AddSeconds(time))
                                                {
                                                    isRun = false;
                                                    break;
                                                }
                                            }
                                        }
                                    }
                                    // sum up what work we've done
                                    Interlocked.Add(ref total, -kill);
                                    kill = 0;
                                    Interlocked.Add(ref count, plus);
                                    plus = 0;

                                    // if we've got enough, stop
                                    if (top > 0 && count >= top)
                                    {
                                        isRun = false;
                                        break;
                                    }
                                }
                            }
                        }
                    }
                });

                // write out completion
                Console.WriteLine(isRun + " " + count + "/" + total + "  " + String.Format("{0:P2}", (double)(count + complete - total) / (double)complete));
                if (printTo != null)
                    printTo.Invoke("100%");
                if (progTo != null)
                    progTo.Invoke(1);

                // sort *all* the builds
                loads = tests.Where(t => t != null).OrderByDescending(r => sort(r.GetStats())).Take((top > 0 ? top : 1));

                // dump everything to console, if nothing to print to
                if (printTo == null)
                    foreach (var l in loads)
                    {
                        Console.WriteLine(l.GetStats().Health + "  " + l.GetStats().Attack + "  " + l.GetStats().Defense + "  " + l.GetStats().Speed
                            + "  " + l.GetStats().CritRate + "%" + "  " + l.GetStats().CritDamage + "%" + "  " + l.GetStats().Resistance + "%" + "  " + l.GetStats().Accuracy + "%");
                    }

                // sadface if no builds
                if (loads.Count() == 0)
                {
                    Console.WriteLine("No builds :(");
                    if (printTo != null)
                        printTo.Invoke("Zero :(");
                }
                else
                {
                    // remember the good one
                    Best = loads.First();
                    foreach (Rune r in Best.Current.runes)
                    {
                        r.manageStats_In = true;
                    }
                    for (int i = 0; i < 6; i++)
                    {
                        if (mon.Current.runes[i] != null && mon.Current.runes[i].ID != Best.Current.runes[i].ID)
                            mon.Current.runes[i].Swapped = true;
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Error " + e);
                if (printTo != null)
                    printTo.Invoke(e.ToString());
            }
        }
Esempio n. 30
0
        /// <summary>
        /// 各個体の評価 修正PFで評価
        /// </summary>
        private void CalcFitness(Tree individual, string buySQL)
        {
            var fitness    = new Fitness();
            var sqlConn    = @"Data Source=.\SQLEXPRESS;Initial Catalog=FXData;Integrated Security=True;Connection Timeout=30;";
            var db         = new DataBase(sqlConn);
            var condition  = " NextPrice * 3 >= TenMaxDD AND NextPrice * 2 > TenAfterPrice AND TenAfterPrice > NextPrice / 2";
            var afterPrice = "TenAfterPrice";
            var maxDD      = "TenMaxDD";

            if (buySQL == "")
            {
                var gprSql     = $"SELECT TOP {MaxRecord + 1} AsOfDate, NextPrice, {afterPrice}, {maxDD} FROM IndexData WHERE {individual.BuySQLString} AND {condition}";
                var table      = db.ExecuteReader(gprSql);
                var tradeCount = table == null || table.Rows == null ? 0 : table.Rows.Count;
                //極端に少ないものは除外
                //極端に多いものは除外
                if (tradeCount < MinRecord || tradeCount > MaxRecord)
                {
                    individual.FitnessInfo = null;
                    return;
                }

                var win = table.AsEnumerable().Where(row => double.Parse(row["NextPrice"].ToString()) < double.Parse(row[afterPrice].ToString())).Count();
                fitness.TradeCount = tradeCount;
                fitness.WinCount   = win;

                var startDate = new DateTime(2002, 1, 1);
                var endDate   = new DateTime(2016, 12, 31);

                //BRACテスト
                while (startDate < endDate)
                {
                    var filterData = table.AsEnumerable().Where(row => DateTime.Parse(row["AsOfDate"].ToString()) < startDate || startDate.AddYears(1) < DateTime.Parse(row["AsOfDate"].ToString()));
                    try
                    {
                        var gain     = filterData.Select(row => double.Parse(row[afterPrice].ToString()) / double.Parse(row["NextPrice"].ToString()) - 1.0).Average();
                        var pain     = filterData.Select(row => 1.0 - double.Parse(row[maxDD].ToString()) / double.Parse(row["NextPrice"].ToString())).Average();
                        var tradeNum = filterData.Count();

                        fitness.TradeCountList.Add(tradeCount - tradeNum);
                        fitness.PFList.Add(gain / pain);
                        fitness.GainList.Add(gain);
                        fitness.PainList.Add(pain);
                        startDate = startDate.AddYears(1);
                    }
                    catch (Exception e)
                    {
                        individual.FitnessInfo = null;
                        return;
                    }
                }
            }
            else
            {
                if (buyTable == null)
                {
                    var gprSql = $"SELECT TOP {MaxRecord + 1} CodeNum, AsOfDate, NextPrice, {afterPrice}, {maxDD}  FROM StockData WHERE {buySign} AND {condition}";
                    buyTable = db.ExecuteReader(gprSql);
                }

                fitness.TradeCount = buyTable.Rows.Count;
                var win = 0;

                var startDate = new DateTime(2007, 1, 1);
                var endDate   = new DateTime(2016, 12, 31);

                //AsOfDate,NextPrice,SellPrice,TenMaxDD
                //始値で買い,売りサインの次の日の始値で売る
                var list = new SynchronizedCollection <object[]>();
                //foreach(DataRow row in table.Rows)
                Parallel.ForEach(buyTable.AsEnumerable(), row =>
                {
                    var sql   = $"SELECT TOP 1 AsOfDate, NextPrice FROM StockData WHERE CodeNum = '{row["CodeNum"].ToString()}' AND AsOfDate > '{DateTime.Parse(row["AsOfDate"].ToString())}' AND AsOfDate < '{DateTime.Parse(row["AsOfDate"].ToString()).AddDays(afterPrice == "TenAfterPrice" ? 20 : 10)}' AND {individual.SellSQLString} AND {condition} AND NowPrice > {row["NextPrice"].ToString()}";
                    var temp  = db.ExecuteReader(sql);
                    sql       = $"SELECT TOP 1 AsOfDate, NextPrice FROM StockData WHERE CodeNum = '{row["CodeNum"].ToString()}' AND AsOfDate > '{DateTime.Parse(row["AsOfDate"].ToString())}' AND AsOfDate < '{DateTime.Parse(row["AsOfDate"].ToString()).AddDays(afterPrice == "TenAfterPrice" ? 20 : 10)}' AND {individual.SellLCSQLString} AND {condition} AND NowPrice < {row["NextPrice"].ToString()}";
                    var temp2 = db.ExecuteReader(sql);

                    if ((temp == null || temp.Rows == null || temp.Rows.Count == 0) & (temp2 == null || temp2.Rows == null || temp2.Rows.Count == 0))
                    {
                        //データなし
                        list.Add(new object[] { DateTime.Parse(row["AsOfDate"].ToString()), double.Parse(row["NextPrice"].ToString()), double.Parse(row[afterPrice].ToString()), double.Parse(row[maxDD].ToString()) });
                    }
                    else
                    {
                        DataTable result = null;
                        if (temp == null || temp.Rows == null || temp.Rows.Count == 0)
                        {
                            result = temp2;
                        }
                        else if (temp2 == null || temp2.Rows == null || temp2.Rows.Count == 0)
                        {
                            result = temp;
                        }
                        else
                        {
                            result = DateTime.Parse(temp.Rows[0]["AsOfDate"].ToString()) < DateTime.Parse(temp2.Rows[0]["AsOfDate"].ToString()) ? temp : temp2;
                        }
                        //データあり
                        var sql2 = $"SELECT MIN(LowValue) FROM Code{row["CodeNum"].ToString()} WHERE Date > '{DateTime.Parse(row["AsOfDate"].ToString())}' AND Date <= '{DateTime.Parse(result.Rows[0]["AsOfDate"].ToString())}'";
                        var dd   = db.ExecuteScalar(sql2, -1.0);
                        var sql3 = $"SELECT ShareUnitNum FROM ShareUnitTable WHERE CodeNum = '{row["CodeNum"].ToString()}'";
                        var unit = db.ExecuteScalar(sql3, -1);
                        if (dd == -1 || unit == -1)
                        {
                            list.Add(new object[] { DateTime.Parse(row["AsOfDate"].ToString()), double.Parse(row["NextPrice"].ToString()), double.Parse(row[afterPrice].ToString()), double.Parse(row[maxDD].ToString()) });
                            return;
                        }
                        list.Add(new object[] { DateTime.Parse(row["AsOfDate"].ToString()), double.Parse(row["NextPrice"].ToString()), double.Parse(result.Rows[0]["NextPrice"].ToString()), dd * unit });
                    }
                });

                //BRACテスト
                while (startDate < endDate)
                {
                    var filterData = list.Where(row => (DateTime)row[0] < startDate || startDate.AddYears(1) < (DateTime)row[0]);
                    try
                    {
                        var gain     = filterData.Select(row => (double)row[2] / (double)row[1] - 1.0).Average();
                        var pain     = filterData.Select(row => 1.0 - (double)row[3] / (double)row[1]).Average();
                        var tradeNum = filterData.Count();

                        fitness.TradeCountList.Add(fitness.TradeCount - tradeNum);
                        fitness.PFList.Add(gain / pain);
                        fitness.GainList.Add(gain);
                        fitness.PainList.Add(pain);
                        startDate = startDate.AddYears(1);
                    }
                    catch (Exception e)
                    {
                        individual.FitnessInfo = null;
                        return;
                    }
                }

                fitness.WinCount = list.Where(row => (double)row[1] < (double)row[2]).Count();
            }

            individual.FitnessInfo = fitness;
        }
Esempio n. 31
0
        /// <summary>
        /// Фиксация информации об исключении
        /// </summary>
        /// <param name="ex">Исключение, которое требуется зафиксировать</param>
        /// <param name="async">Выполинть запись асинхронно</param>
        internal void WriteEx(Exception ex, bool async)
        {
            lock (_sentMessages.SyncRoot)
            {
                try
                {
                    SentMessage[] tmp = _sentMessages.Where(x => x.DtCreate <= DateTime.Now.AddMinutes(-1 * SKIP_MESS_MINUTE)).ToArray();
                    tmp.Select(x => _sentMessages.Remove(x)).ToArray();
                }
                catch { }
            }

            if (ex == null)
            {
                return;
            }

            XmlElement xml = GetErrorXml(ex);

            if (((XmlElement)xml.SelectSingleNode("Info")).GetAttribute("mail") == "1")
            {
                // Заголовок - используется для автоматической разборки писем на сервере
                string subject = "";

                string pr = ((XmlElement)xml.SelectSingleNode("Info/Node[@id='Priority']")).GetAttribute("value");
                if (pr == Enum.GetName(typeof(Priority), Priority.Error))
                {
                    subject = "AppError";

                    // Доп. проверка на ExternalError
                    pr = GetPriority(ex, Priority.Error).ToString();
                    ((XmlElement)xml.SelectSingleNode("Info/Node[@id='Priority']")).SetAttribute("value", pr);
                }
                if (pr == Enum.GetName(typeof(Priority), Priority.ExternalError))
                {
                    subject = "Error ";
                }
                else if (pr == Enum.GetName(typeof(Priority), Priority.Info) || pr == Enum.GetName(typeof(Priority), Priority.Alarm))
                {
                    subject = "*" + pr + "* ";
                }

                if (string.IsNullOrEmpty(_domain_name) && (pr == Enum.GetName(typeof(Priority), Priority.ExternalError) || pr == Enum.GetName(typeof(Priority), Priority.Alarm)))
                {
                    return;
                }

                XmlElement component = (XmlElement)xml.SelectSingleNode("Info/Node[@id='Component']");
                string     build     = component != null?component.GetAttribute("value") : "";

                subject += String.Format((pr == Enum.GetName(typeof(Priority), Priority.Error) ? "[{0}]{1}:{2}" : "{2}"), _appName,
                                         (build != "" ? "[" + build + "]" : ""),
                                         ((XmlElement)xml.SelectSingleNode("Info")).GetAttribute("message")).Replace("\n", " ").Replace("\r", " ");

                if (subject.Length > MaxSubjLen)
                {
                    subject = subject.Substring(0, MaxSubjLen);
                }

                XmlElement  func = ((XmlElement)xml.SelectSingleNode("Info/Node[@id='Function']"));
                XmlElement  host = ((XmlElement)xml.SelectSingleNode("Info/Node[@id='Computer']"));
                XmlElement  user = ((XmlElement)xml.SelectSingleNode("Info/Node[@id='Computer']"));
                SentMessage sm   = new SentMessage((host != null ? host.GetAttribute("value") : ""), (user != null ? user.GetAttribute("value") : ""), (func != null ? func.GetAttribute("value") : ""), subject);
                lock (_sentMessages.SyncRoot)
                {
                    try
                    {
                        if (_sentMessages.FirstOrDefault(x => x.Equals(sm)) != null)
                        {
                            return;
                        }
                        _sentMessages.Add(sm);
                    }
                    catch { }
                }

                // Очистка информации о внутренней структуре приложения(стэк/ информацию о сборках) для внешних ошибок.
                if (pr == Enum.GetName(typeof(Priority), Priority.ExternalError))
                {
                    XmlElement excpt = ((XmlElement)xml.SelectSingleNode("Exceptions"));
                    if (excpt != null)
                    {
                        foreach (XmlElement exc in excpt.ChildNodes)
                        {
                            XmlElement cmpt = ((XmlElement)exc.SelectSingleNode("Node[@id='Component']"));
                            if (cmpt != null)
                            {
                                exc.RemoveChild(cmpt);
                            }
                            XmlElement mthd = ((XmlElement)exc.SelectSingleNode("Node[@id='Method']"));
                            if (mthd != null)
                            {
                                exc.RemoveChild(mthd);
                            }
                            XmlElement trce = ((XmlElement)exc.SelectSingleNode("Node[@id='Trace']"));
                            if (trce != null)
                            {
                                exc.RemoveChild(trce);
                            }
                        }
                        XmlElement info = ((XmlElement)xml.SelectSingleNode("Info"));
                        XmlElement frmw = ((XmlElement)xml.SelectSingleNode("Info/Node[@id='Framework']"));
                        if (frmw != null)
                        {
                            info.RemoveChild(frmw);
                        }
                        XmlElement memuse = ((XmlElement)xml.SelectSingleNode("Info/Node[@id='MemoryUsed']"));
                        if (memuse != null)
                        {
                            info.RemoveChild(memuse);
                        }
                    }
                }

                // Отправка письма
                IncState(1);

                if (async)
                {
                    TaskMailSend task = new TaskMailSend(this, subject, xml);
                    task.Execute();
                }
                else
                {
                    SendMail(subject, xml);
                }
            }
        }
Esempio n. 32
0
        private void AnalyzeARP(Packet packet)
        {
            if (!(packet.PayloadPacket is ARPPacket))
            {
                return;
            }
            if (!(packet is EthernetPacket))
            {
                return;
            }

            EthernetPacket ethernet = (EthernetPacket)packet;
            ARPPacket      arp      = (ARPPacket)packet.PayloadPacket;

            // Si el paquete va dirigido a nuestra MAC...
            if (ethernet.DestinationHwAddress.Equals(localPhysicalAddress))
            {
                PhysicalAddress mac = arp.SenderHardwareAddress;
                IPAddress       ip  = arp.SenderProtocolAddress;

                Neighbor neighbor = Program.CurrentProject.data.GetNeighbor(mac);
                if (neighbor == null)
                {
                    // Creamos el vecino
                    neighbor = new Neighbor();
                    neighbor.physicalAddress = mac;
                    neighbor.AddIP(ip);
                    Program.CurrentProject.data.AddNeighbor(neighbor);
                    NewNeighbor(this, new NeighborEventArgs(neighbor));
                }
                else
                {
                    // Si ya existe, comprobamos si tiene la iP ipv4 y se la añadimos (en caso de que lo la tenga)
                    if (!neighbor.ExistsIP(ip))
                    {
                        neighbor.AddIP(ip);
                        Program.CurrentProject.data.AddNeighbor(neighbor);
                    }
                }
            }
            // Si va dirigido a broadcast ...
            else if (ethernet.DestinationHwAddress.Equals(PhysicalAddress.Parse("FF-FF-FF-FF-FF-FF")))
            {
                // Si los que están "negociando" las tablas ARP están siendo atacados por un MITM,
                // se les vuelve a atacar envenenando sus tablas

                if (arp.Operation == ARPOperation.Request)
                {
                    PhysicalAddress senderMac      = arp.SenderHardwareAddress;
                    PhysicalAddress destinationMac = arp.TargetHardwareAddress;
                    IPAddress       senderIp       = arp.SenderProtocolAddress;
                    IPAddress       destinationIp  = arp.TargetProtocolAddress;

                    SynchronizedCollection <Attack> lstAttacks = Program.CurrentProject.data.GetAttacks();

                    // En caso de MITM ARP -> Si el equipo está intentando restablecer su tabla ARP ... se le vuelve a envenenar
                    foreach (Attack attk in lstAttacks.Where(A => (A.attackType == AttackType.ARPSpoofing || A.attackType == AttackType.InvalidMacSpoofIpv4) && A.attackStatus == AttackStatus.Attacking))
                    {
                        if (attk is MitmAttack)
                        {
                            MitmAttack mitmArp = (MitmAttack)attk;
                            if (
                                ((mitmArp.t1.ip.Equals(senderIp)) || (mitmArp.t1.ip.Equals(destinationIp)))
                                &&
                                ((mitmArp.t2.ip.Equals(senderIp)) || (mitmArp.t2.ip.Equals(destinationIp)))
                                )
                            {
                                // Lo envia a ambas partes del ataque, se vuelve a envenenar a los dos equipos
                                // (aunque unicamente sería necesario al que hace la solicitud (request)

                                ethernet = Attacks.ARPSpoofing.GenerateResponseArpPoison(device.Interface.MacAddress,
                                                                                         ((MitmAttack)mitmArp).t2.mac,
                                                                                         ((MitmAttack)mitmArp).t2.ip,
                                                                                         ((MitmAttack)mitmArp).t1.ip);
                                Program.CurrentProject.data.SendPacket(ethernet);

                                ethernet = Attacks.ARPSpoofing.GenerateResponseArpPoison(device.Interface.MacAddress,
                                                                                         ((MitmAttack)mitmArp).t1.mac,
                                                                                         ((MitmAttack)mitmArp).t1.ip,
                                                                                         ((MitmAttack)mitmArp).t2.ip);
                                Program.CurrentProject.data.SendPacket(ethernet);
                            }
                        }
                        else if (attk is InvalidMacSpoofAttackIpv4Attack)
                        {
                            ethernet = Attacks.ARPSpoofing.GenerateResponseArpPoison(device.Interface.MacAddress,
                                                                                     ((InvalidMacSpoofAttackIpv4Attack)attk).t2.mac,
                                                                                     ((InvalidMacSpoofAttackIpv4Attack)attk).t2.ip,
                                                                                     ((InvalidMacSpoofAttackIpv4Attack)attk).t1.ip);
                            Program.CurrentProject.data.SendPacket(ethernet);
                        }
                    }
                }
            }

            OnNewARP(new ArpEventArgs(packet));
        }