コード例 #1
0
        public void OnGet()
        {
            SnortContext db = HttpContext.RequestServices.GetService(typeof(SnortContext)) as SnortContext;

            if (StaticData.sensors == null)
            {
                StaticData.sensors = SensorTable.GetSensors(db.GetConnection());
            }

            if (StaticData.alerts == null)
            {
                StaticData.alerts = AlertMapper.ResolveAlerts(0, ref StaticData.signatureStrings, db.GetConnection());
            }

            alerts = StaticData.alerts;
            if (HttpContext.Request.Query.Count > 0)
            {
                Filtering.applyFilter(ref alerts, HttpContext.Request.Query);
                filtered = true;
            }

            protocols        = Stats.ByProtocol(alerts);
            protocols_source = Stats.ByProtocolSource(alerts);
            ;
        }
コード例 #2
0
        public void OnGet()
        {
            SnortContext db = HttpContext.RequestServices.GetService(typeof(SnortContext)) as SnortContext;

            if (StaticData.sensors == null)
            {
                StaticData.sensors = SensorTable.GetSensors(db.GetConnection());
            }

            if (StaticData.alerts == null)
            {
                StaticData.alerts = AlertMapper.ResolveAlerts(0, ref StaticData.signatureStrings, db.GetConnection());
                foreach (Alert a in StaticData.alerts)
                {
                    if (StaticData.iplocations.ContainsKey(a.src_ip))
                    {
                        continue;
                    }
                    else
                    {
                        StaticData.iplocations[a.src_ip] = "new";
                    }
                }
            }

            else
            {
                lastTime = StaticData.alerts.Select(x => x.time).DefaultIfEmpty(DateTime.MinValue).Max();
                //Check for new events
                List <Alert>          new_alerts = new List <Alert>();
                Dictionary <int, int> lastAlers  = new Dictionary <int, int>();
                foreach (Sensor s in StaticData.sensors)
                {
                    int lastEvent = StaticData.alerts.Where(x => x.sid == s.sid).Select(x => x.cid).DefaultIfEmpty(0).Max();
                    if (s.last_cid != lastEvent)
                    {
                        new_alerts.AddRange(AlertMapper.UpdateAlerts(s.sid, lastEvent, StaticData.signatureStrings, db.GetConnection()));
                    }
                }
                new_alerts.Sort((alertA, alertB) => DateTime.Compare(alertB.time, alertA.time));
                foreach (Alert a in new_alerts)
                {
                    if (StaticData.iplocations.ContainsKey(a.src_ip))
                    {
                        continue;
                    }
                    else
                    {
                        StaticData.iplocations[a.src_ip] = "new";
                    }
                }
                StaticData.alerts.InsertRange(0, new_alerts);
            }
            if (HttpContext.Request.Query.Count > 0)
            {
                //Filtering.applyFilter(ref alerts, HttpContext.Request.Query);
                filtered = true;
            }
        }
コード例 #3
0
        public async Task <ActionResult> OnPostPcap(int cid, int sid, string source, string dest, string output)
        {
            SnortContext db = HttpContext.RequestServices.GetService(typeof(SnortContext)) as SnortContext;

            Utils.Tcpdump tcpdump_path = HttpContext.RequestServices.GetService(typeof(Utils.Tcpdump)) as Utils.Tcpdump;
            string        path         = tcpdump_path.path;

            if (StaticData.alerts == null)
            {
                StaticData.alerts = AlertMapper.ResolveAlerts(0, ref StaticData.signatureStrings, db.GetConnection());
            }

            //alerts = SessionExtensions.Get<List<Alert>>(HttpContext.Session,"alert");
            this.cid = cid;
            this.sid = sid;
            alerts.Add(StaticData.alerts.Where(x => x.cid == cid && x.sid == sid).FirstOrDefault());

            targetSec = ((DateTimeOffset)alerts.First().time).ToUnixTimeSeconds();

            long epochTicks = new DateTime(1970, 1, 1).Ticks;

            targetMS = alerts.First().time.Ticks - epochTicks;
            //TimeSpan epochTicks2 = new TimeSpan(new DateTime(1970, 1, 1).Ticks);
            //targetMS = (ulong) (((DateTimeOffset)alerts.First().time).Ticks - epochTicks2.Ticks)/10;

            IEnumerable <string> files;

            try
            {
                files = Directory.EnumerateFiles(path, "tcpdump.log.*");
            }
            catch (Exception)
            {
                return(RedirectToPage("Error", "Issue", new { issue = "Snort packet log folder not found (" + path + "). Change the path in appsettings.json to match the Snort output path." }));
            }

            long   closestTS   = 0;
            string closestFile = "";

            foreach (string f in files)
            {
                //ulong currentTS = Convert.ToUInt64(f.Split('.').Last());
                long currentTSS = Convert.ToInt64(f.Split('.').Last());
                //DateTime currentTS = Convert.ToDateTime(f.Split('.').Last());
                if (currentTSS <= targetSec && currentTSS > closestTS)
                {
                    closestTS   = currentTSS;
                    closestFile = f;
                }
            }
            if (closestFile == "")
            {
                return(RedirectToPage("Error", "Issue", new { issue = "No appropriate packet log found in " + path + ". Please review your Snort output configuration and activate: output log_tcpdump: tcpdump.log" }));
            }
            string dir = Path.Combine(Startup.AppPath, "wwwroot/pcaps/");

            if (!System.IO.File.Exists(dir + sid + "." + cid))
            {
                (new FileInfo(dir + sid + "." + cid)).Directory.Create();
                //CaptureDeviceList devices = CaptureDeviceList.Instance;
                CaptureFileReaderDevice device = new CaptureFileReaderDevice(closestFile);
                captureFileWriter = new CaptureFileWriterDevice(dir + sid + "." + cid);
                captureFileWriter.Open();
                device.OnPacketArrival  += new PacketArrivalEventHandler(this.device_OnPacketArrival);
                device.OnCaptureStopped += new CaptureStoppedEventHandler(this.device_OnCaptureStopped);
                device.Filter            = "host " + source + " and host " + dest;
                device.StartCapture();

                signal = new SemaphoreSlim(0, 1);
                await signal.WaitAsync();
            }
            switch (output)
            {
            case "pcap":
            {
                return(File("/pcaps/" + sid + "." + cid, "application/octet-stream",
                            sid + "." + cid + ".pcap"));
            }

            case "tcpdump":
            {
                string tcpdump = Utils.Bash("tcpdump -r " + dir + sid + "." + cid);
                return(File(new MemoryStream(Encoding.UTF8.GetBytes(tcpdump ?? "tcpdump is not available")), "application/octet-stream",
                            sid + "." + cid + ".txt"));
            }

            default:
            {
                return(File("/pcaps/" + sid + "." + cid, "application/octet-stream",
                            sid + "." + cid + ".pcap"));
            }
            }
        }
コード例 #4
0
        public async void extractFromPcap(int cid, int sid)
        {
            string       dir = Path.Combine(Startup.AppPath, "wwwroot/pcaps/");
            SnortContext db  = HttpContext.RequestServices.GetService(typeof(SnortContext)) as SnortContext;

            Utils.Tcpdump tcpdump_path = HttpContext.RequestServices.GetService(typeof(Utils.Tcpdump)) as Utils.Tcpdump;
            string        path         = tcpdump_path.path;

            if (StaticData.alerts == null)
            {
                StaticData.alerts = AlertMapper.ResolveAlerts(0, ref StaticData.signatureStrings, db.GetConnection());
            }

            //alerts = SessionExtensions.Get<List<Alert>>(HttpContext.Session,"alert");
            this.cid = cid;
            this.sid = sid;
            alerts.Add(StaticData.alerts.Where(x => x.cid == cid && x.sid == sid).FirstOrDefault());

            //UTC
            targetSec = ((DateTimeOffset)alerts.First().time).ToUnixTimeSeconds();

            //Local Time
            //TimeSpan epochSecs = new TimeSpan(new DateTime(1970, 1, 1).Second);
            //targetSec = (((DateTimeOffset)alerts.First().time).Second - epochSecs.Seconds);

            if (!System.IO.File.Exists(dir + sid + "." + cid))
            {
                string source = StaticData.alerts.Where(x => x.cid == cid && x.sid == sid).FirstOrDefault().src_ip;
                string dest   = StaticData.alerts.Where(x => x.cid == cid && x.sid == sid).FirstOrDefault().dest_ip;

                long epochTicks = new DateTime(1970, 1, 1).Ticks;
                targetMS = alerts.First().time.Ticks - epochTicks;
                //TimeSpan epochTicks2 = new TimeSpan(new DateTime(1970, 1, 1).Ticks);
                //targetMS = (ulong) (((DateTimeOffset)alerts.First().time).Ticks - epochTicks2.Ticks)/10;

                IEnumerable <string> files;
                try
                {
                    files = Directory.EnumerateFiles(path, "tcpdump.log.*");


                    long   closestTS   = 0;
                    string closestFile = "";

                    foreach (string f in files)
                    {
                        //ulong currentTS = Convert.ToUInt64(f.Split('.').Last());
                        long currentTSS = Convert.ToInt64(f.Split('.').Last());
                        //DateTime currentTS = Convert.ToDateTime(f.Split('.').Last());
                        if (currentTSS <= targetSec && currentTSS > closestTS)
                        {
                            closestTS   = currentTSS;
                            closestFile = f;
                        }
                    }

                    (new FileInfo(dir + sid + "." + cid)).Directory.Create();
                    //CaptureDeviceList devices = CaptureDeviceList.Instance;
                    CaptureFileReaderDevice device = new CaptureFileReaderDevice(closestFile);
                    captureFileWriter = new CaptureFileWriterDevice(dir + sid + "." + cid);
                    captureFileWriter.Open();
                    device.OnPacketArrival  += new PacketArrivalEventHandler(this.device_OnPacketArrival);
                    device.OnCaptureStopped += new CaptureStoppedEventHandler(this.device_OnCaptureStopped);
                    device.Filter            = "host " + source + " and host " + dest;
                    device.StartCapture();

                    signal = new SemaphoreSlim(0, 1);
                    await signal.WaitAsync();
                }
                catch (Exception) {; }
            }
        }
コード例 #5
0
        public void OnGet()
        {
            try
            {
                cid = Convert.ToInt32(HttpContext.Request.Query["cid"].ToString());
                sid = Convert.ToInt32(HttpContext.Request.Query["sid"].ToString());
            }
            catch (Exception)
            {
                errors = new List <string>();
                errors.Add("How did you get here? Invalid url.");
                //errors.Add(e.Message);
                return;
            }

            SnortContext db = HttpContext.RequestServices.GetService(typeof(SnortContext)) as SnortContext;

            if (StaticData.alerts == null)
            {
                StaticData.alerts = AlertMapper.ResolveAlerts(0, ref StaticData.signatureStrings, db.GetConnection());
            }
            //Check for new alerts
            else
            {
            }

            if (StaticData.ref_classes == null)
            {
                StaticData.ref_classes = Reference_systemTable.GetRefClasses(db.GetConnection());
            }
            if (StaticData.class_names == null)
            {
                StaticData.class_names = Sig_classTable.GetClassNames(db.GetConnection());
            }
            if (StaticData.protocols == null)
            {
                StaticData.protocols = XmlUtils.GetProcotols();
                //StaticData.protocols = db.GetProtocols();
            }
            if (StaticData.trprotocols == null)
            {
                StaticData.trprotocols = XmlUtils.GetTransportProcotols();
            }

            alerts.Add(StaticData.alerts.Where(x => x.cid == cid && x.sid == sid).FirstOrDefault());
            //SessionExtensions.Set<List<Alert>>(HttpContext.Session,"alert", alerts);

            eve = EventTable.GetEvent(cid, sid, db.GetConnection());
            if (eve.cid == 0)
            {
                errors = new List <string>();
                errors.Add("How did you get here? Event not found.");
                //errors.Add(e.Message);
                return;
            }

            //SIGNATURE
            Signature signature = SignatureTable.GetSignature(eve.signature, db.GetConnection());

            if (signature.sig_class_id > 0)
            {
                StaticData.class_names.TryGetValue(signature.sig_class_id, out className);
                signature.class_name = className;
                signatures.Add(signature);
            }
            sigrefs = ReferenceTable.GetReference(signature.sig_id, db.GetConnection());
            if (sigrefs != null)
            {
                foreach (snortdb.Ref sigref in sigrefs)
                {
                    string ref_url = StaticData.ref_classes.GetValueOrDefault(sigref.ref_system_id) + sigref.ref_tag;
                    if (!ref_url.StartsWith("http"))
                    {
                        signature.ref_url += "<a href=http://" + ref_url + " target=\"_blank\">" + ref_url + "</a></br>";
                    }
                    else
                    {
                        signature.ref_url += "<a href=" + ref_url + " target=\"_blank\">" + ref_url + "</a></br>";
                    }
                }
            }
            else
            {
                signature.ref_url = "-";
            }

            //IP HEADER
            Iphdr iphdr = IphdrTable.GetIphdr(cid, sid, db.GetConnection());

            if (iphdr.source == null)
            {
                iphdr.source = AlertMapper.ResolveIP(iphdr.ip_src);
            }
            if (iphdr.destination == null)
            {
                iphdr.destination = AlertMapper.ResolveIP(iphdr.ip_dst);
            }
            string protocol  = StaticData.protocols.Where(x => x.pid == iphdr.ip_proto).Select(x => x.name).FirstOrDefault();
            string proto_ref = StaticData.protocols.Where(x => x.pid == iphdr.ip_proto).Select(x => x.reference).FirstOrDefault();

            if (protocol != null)
            {
                if (proto_ref == null)
                {
                    iphdr.protocol = protocol;
                }
                else
                {
                    iphdr.protocol = "<a href=\"" + proto_ref + "\" target=\"_blank\">" + protocol + "</a>";
                }
            }
            else
            {
                iphdr.protocol = iphdr.ip_proto.ToString();
            }
            iphdrs.Add(iphdr);


            switch (iphdr.ip_proto)
            {
            case 1:          //ICMP HEADER
            {
                Icmphdr icmphdr = IcmphdrTable.GetIcmphdr(cid, sid, db.GetConnection());

                //icmphdr.icmp_type_text = Utils.Bash("cat " + path + " | grep '#" + icmphdr.icmp_type + " –'");
                icmphdr.icmp_type_text = Utils.GetICMPType(icmphdr.icmp_type.ToString());
                icmphdrs.Add(icmphdr);
                break;
            }

            case 6:          //TCP HEADER
            {
                Tcphdr tcphdr = TcphdrTable.GetTcphdr(cid, sid, db.GetConnection());
                //var output = Utils.Bash("cat /etc/services | grep [[:space:]]" + tcphdr.tcp_sport + "/tcp");
                //var output2 = Utils.Bash("cat /etc/services | grep [[:space:]]" + tcphdr.tcp_dport + "/tcp");
                TransportProtocol trp  = StaticData.trprotocols.Where(x => x.number == tcphdr.tcp_sport && x.protocol == "tcp").FirstOrDefault();
                TransportProtocol trp2 = StaticData.trprotocols.Where(x => x.number == tcphdr.tcp_dport && x.protocol == "tcp").FirstOrDefault();
                /*if(output != "")    */
                if (trp != null)
                {
                    if (trp.xref != null)
                    {
                        tcphdr.tcp_protocol = "<a href=\"" + trp.xref + "\" target=\"_blank\">" + trp.name + "</a>";
                    }
                    else
                    {
                        tcphdr.tcp_protocol = trp.name;
                    }
                    // tcphdr.tcp_protocol = tcphdr.tcp_sport + " ("+ output.Split('\t')[0] + ")";
                    // if(output.Split('#').Count() > 1) tcphdr.tcp_protocol += " – " + output.Split('#')[1];
                }
                else
                {
                    tcphdr.tcp_protocol = tcphdr.tcp_sport.ToString();
                }
                /*if(output2 != "") */
                if (trp2 != null)
                {
                    if (trp2.xref != null)
                    {
                        tcphdr.tcp_protocol2 = "<a href=\"" + trp2.xref + "\" target=\"_blank\">" + trp2.name + "</a>";
                    }
                    else
                    {
                        tcphdr.tcp_protocol2 = trp2.name;
                    }
                    // tcphdr.tcp_protocol2 = tcphdr.tcp_dport + " ("+ output2.Split('\t')[0] + ")";
                    // if(output2.Split('#').Count() > 1) tcphdr.tcp_protocol2 += " – " + output2.Split('#')[1];
                }
                else
                {
                    tcphdr.tcp_protocol2 = tcphdr.tcp_dport.ToString();
                }
                tcphdrs.Add(tcphdr);
                break;
            }

            case 17:          //UDP HEADER
            {
                Udphdr udphdr = UdphdrTable.GetUdphdr(cid, sid, db.GetConnection());
                //var output = Utils.Bash("cat /etc/services | grep [[:space:]]" + udphdr.udp_sport + "/udp");
                //var output2 = Utils.Bash("cat /etc/services | grep [[:space:]]" + udphdr.udp_dport + "/udp");

                TransportProtocol trp  = StaticData.trprotocols.Where(x => x.number == udphdr.udp_sport && x.protocol == "udp").FirstOrDefault();
                TransportProtocol trp2 = StaticData.trprotocols.Where(x => x.number == udphdr.udp_dport && x.protocol == "udp").FirstOrDefault();
                /*if(output != "") */
                if (trp != null)
                {
                    //  udphdr.udp_protocol = udphdr.udp_sport + " ("+ output.Split('\t')[0] + ")";
                    //  if(output.Split('#').Count() > 1) udphdr.udp_protocol +=  " – " + output.Split('#')[1];
                    if (trp.xref != null)
                    {
                        udphdr.udp_protocol = "<a href=\"" + trp.xref + "\" target=\"_blank\">" + trp.name + "</a>";
                    }
                    else
                    {
                        udphdr.udp_protocol = trp.name;
                    }
                }
                else
                {
                    udphdr.udp_protocol = udphdr.udp_sport.ToString();
                }


                /*if(output2 != "") */
                if (trp2 != null)
                {
                    //udphdr.udp_protocol2 = udphdr.udp_dport + " ("+ output2.Split('\t')[0] + ")";
                    //if(output2.Split('#').Count() > 1) udphdr.udp_protocol2 +=  " – " + output2.Split('#')[1];
                    if (trp2.xref != null)
                    {
                        udphdr.udp_protocol2 = "<a href=\"" + trp2.xref + "\" target=\"_blank\">" + trp2.name + "</a>";
                    }
                    else
                    {
                        udphdr.udp_protocol2 = trp2.name;
                    }
                }
                else
                {
                    udphdr.udp_protocol2 = udphdr.udp_dport.ToString();
                }
                udphdrs.Add(udphdr);
                break;
            }

            default:
            {
                break;
            }
            }


            //WHOIS - RIPE
            using (WebClient wc = new WebClient())
            {
                snortdb.Attributes attList = new snortdb.Attributes();
                try     //SOURCE
                {
                    string url = "https://rest.db.ripe.net/search.xml?query-string=" + iphdr.source +
                                 "&flags=no-filtering&source=RIPE";
                    var json = wc.DownloadString(url);

                    XmlDocument xdoc = new XmlDocument();
                    xdoc.LoadXml(json);
                    XmlNode root = xdoc.DocumentElement;
                    attList.attributes = new List <snortdb.Attribute>();
                    foreach (XmlNode record in root.SelectNodes("objects/object"))
                    {
                        if (record.Attributes["type"].Value == "inetnum" || record.Attributes["type"].Value == "inet6num" || record.Attributes["type"].Value == "person" ||
                            record.Attributes["type"].Value == "route")
                        {
                            foreach (XmlNode att in record.SelectNodes(@"attributes/attribute"))
                            {
                                if (att.Attributes["name"].Value == "remarks")
                                {
                                    continue;
                                }
                                attList.attributes.Add(new snortdb.Attribute(att.Attributes["name"].Value, att.Attributes["value"].Value));
                            }
                        }
                    }
                    if (attList.attributes.Count() > 0)
                    {
                        whoisURL = "https://apps.db.ripe.net/db-web-ui/#/query?searchtext=" + iphdr.source + "&source=RIPE&bflag=true";
                        attList.attributes.Add(new snortdb.Attribute("source url", "<a href=\"" + whoisURL + "\" target=\"_blank\">" + whoisURL + "<a>"));
                        whoisData.Add(new AttributeOutput(String.Join("<br>", attList.attributes.Select(x => x.name)), String.Join("<br>", attList.attributes.Select(x => x.value))));
                    }
                }
                catch (Exception) { }

                attList.attributes.Clear();
                try     //DESTINATION
                {
                    string url = "https://rest.db.ripe.net/search.xml?query-string=" + iphdr.destination +
                                 "&flags=no-filtering&source=RIPE";
                    var json = wc.DownloadString(url);

                    XmlDocument xdoc = new XmlDocument();
                    xdoc.LoadXml(json);
                    XmlNode root = xdoc.DocumentElement;
                    attList.attributes = new List <snortdb.Attribute>();
                    foreach (XmlNode record in root.SelectNodes("objects/object"))
                    {
                        if (record.Attributes["type"].Value == "inetnum" || record.Attributes["type"].Value == "inet6num" || record.Attributes["type"].Value == "person" ||
                            record.Attributes["type"].Value == "route")
                        {
                            foreach (XmlNode att in record.SelectNodes(@"attributes/attribute"))
                            {
                                if (att.Attributes["name"].Value == "remarks")
                                {
                                    continue;
                                }
                                attList.attributes.Add(new snortdb.Attribute(att.Attributes["name"].Value, att.Attributes["value"].Value));
                            }
                        }
                    }
                    if (attList.attributes.Count() > 0)
                    {
                        whoisURL2 = "https://apps.db.ripe.net/db-web-ui/#/query?searchtext=" + iphdr.destination + "&source=RIPE&bflag=true";
                        attList.attributes.Add(new snortdb.Attribute("source url", "<a href=\"" + whoisURL2 + "\" target=\"_blank\">" + whoisURL2 + "<a>"));
                        whoisData2.Add(new AttributeOutput(String.Join("<br>", attList.attributes.Select(x => x.name)), String.Join("<br>", attList.attributes.Select(x => x.value))));
                    }
                }
                catch (Exception) { }
            }

            //SessionExtensions.Set<List<Data>>(HttpContext.Session,"datas", datas);
        }
コード例 #6
0
        public void OnGet()
        {
            try
            {
                SnortContext db = HttpContext.RequestServices.GetService(typeof(SnortContext)) as SnortContext;

                if (StaticData.sensors == null)
                {
                    StaticData.sensors = SensorTable.GetSensors(db.GetConnection());
                }

                if (StaticData.alerts == null)
                {
                    StaticData.alerts = AlertMapper.ResolveAlerts(limit, ref StaticData.signatureStrings, db.GetConnection());
                    foreach (Alert a in StaticData.alerts)
                    {
                        if (StaticData.iplocations.ContainsKey(a.src_ip))
                        {
                            continue;
                        }
                        else
                        {
                            StaticData.iplocations[a.src_ip] = "new";
                        }
                    }
                }

                else
                {
                    lastTime = StaticData.alerts.Select(x => x.time).DefaultIfEmpty(DateTime.MinValue).Max();
                    //Check for new events
                    List <Alert> new_alerts = new List <Alert>();
                    foreach (Sensor s in StaticData.sensors)
                    {
                        int lastEvent = StaticData.alerts.Where(x => x.sid == s.sid).Select(x => x.cid).DefaultIfEmpty(0).Max();
                        if (s.last_cid != lastEvent)
                        {
                            //List<Event> events = EventTable.UpdateEvents(s.sid, lastEvent, db.GetConnection());
                            new_alerts.AddRange(AlertMapper.UpdateAlerts(s.sid, lastEvent, StaticData.signatureStrings, db.GetConnection()));
                        }
                    }
                    foreach (Alert a in new_alerts)
                    {
                        if (StaticData.iplocations.ContainsKey(a.src_ip))
                        {
                            continue;
                        }
                        else
                        {
                            StaticData.iplocations[a.src_ip] = "new";
                        }
                    }
                    new_alerts.Sort((alertA, alertB) => DateTime.Compare(alertB.time, alertA.time));
                    StaticData.alerts.InsertRange(0, new_alerts);
                }
            }
            catch (Exception e)
            {
                error = "Database error: " + e.Message;
                return;
            }
            try {
                int year = 0, month = 0, day = 0;

                DateTime startdate;
                DateTime enddate;

                Microsoft.Extensions.Primitives.StringValues queryVal;
                if (HttpContext.Request.Query.TryGetValue("view", out queryVal))
                {
                    Microsoft.Extensions.Primitives.StringValues yearVal;
                    Microsoft.Extensions.Primitives.StringValues monthVal;
                    Microsoft.Extensions.Primitives.StringValues dayVal;

                    HttpContext.Request.Query.TryGetValue("year", out yearVal);
                    HttpContext.Request.Query.TryGetValue("month", out monthVal);
                    HttpContext.Request.Query.TryGetValue("day", out dayVal);

                    switch (queryVal.FirstOrDefault())
                    {
                    case "year":
                    {
                        int.TryParse(yearVal, out year);
                        months = Stats.ByYear(StaticData.alerts, ref alerts, year);
                        if (year == 0)
                        {
                            year = DateTime.Now.Year;
                        }

                        middleText = year.ToString();
                        int upmonth = StaticData.alerts.Where(x => x.time.Year == year).Select(x => x.time.Month).DefaultIfEmpty().Max();
                        upText  = upmonth.ToString();
                        upQuery = "?view=month&year=" + year + "&month=" + upmonth;
                        if (year < DateTime.Now.Year)
                        {
                            rightText = (year + 1).ToString();
                            leftQuery = "?view=year&year=" + (year + 1);
                        }

                        if (year > StaticData.alerts.Select(x => x.time.Year).DefaultIfEmpty(year).Min())
                        {
                            leftText  = (year - 1).ToString();
                            leftQuery = "?view=year&year=" + (year - 1);
                        }
                        startdate = new DateTime(year, 1, 1);
                        enddate   = new DateTime(year, 12, DateTime.DaysInMonth(year, 12));
                        xLabel    = year.ToString();
                        yLabel    = "%b";
                        break;
                    }

                    case "month":
                    {
                        int.TryParse(yearVal, out year);
                        int.TryParse(monthVal, out month);

                        if (year == 0)
                        {
                            year = DateTime.Now.Year;
                        }
                        if (month == 0)
                        {
                            month = DateTime.Now.Month;
                        }
                        months = Stats.ByMonth(StaticData.alerts, ref alerts, year, month);

                        xLabel = year + " " + CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(month);
                        yLabel = "%d";

                        middleText = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(month).Substring(0, 3) + " " + year;
                        int upday = StaticData.alerts.Where(x => x.time.Year == year && x.time.Month == month).Select(x => x.time.Day).DefaultIfEmpty().Max();
                        upText    = upday.ToString();
                        upQuery   = "?view=day&year=" + year + "&month=" + month + "&day=" + upday;
                        downText  = year.ToString();
                        downQuery = "?view=year&year=" + year;
                        if (month < 12)
                        {
                            if (year == DateTime.Now.Year && month >= DateTime.Now.Month)
                            {
                            }
                            else
                            {
                                rightText  = (month + 1).ToString();
                                rightQuery = "?view=month&year=" + year + "&month=" + (month + 1);
                            }
                        }
                        if (month > 1)
                        {
                            leftText  = (month - 1).ToString();
                            leftQuery = "?view=month&year=" + year + "&month=" + (month - 1);
                        }
                        startdate = new DateTime(year, month, 1);
                        enddate   = new DateTime(year, month, DateTime.DaysInMonth(year, month));
                        break;
                    }

                    case "day":
                    {
                        int.TryParse(yearVal, out year);
                        int.TryParse(monthVal, out month);
                        int.TryParse(dayVal, out day);

                        if (year == 0)
                        {
                            year = DateTime.Now.Year;
                        }
                        if (month == 0)
                        {
                            month = DateTime.Now.Month;
                        }
                        if (day == 0)
                        {
                            day = DateTime.DaysInMonth(year, month);
                        }
                        months = Stats.ByDay(StaticData.alerts, ref alerts, year, month, day);

                        xLabel     = year + " " + CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(month) + " " + day;
                        yLabel     = "%H";
                        middleText = day + " " + CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(month).Substring(0, 3) + " " + year;
                        downText   = month.ToString();
                        downQuery  = "?view=month&year=" + year + "&month=" + month;
                        if (day > 1)
                        {
                            leftText  = (day - 1).ToString();
                            leftQuery = "?view=day&year=" + year + "&month=" + month + "&day=" + (day - 1).ToString();
                        }
                        if (day < DateTime.DaysInMonth(year, month))
                        {
                            if (year == DateTime.Now.Year && month == DateTime.Now.Month && day >= DateTime.Now.Day)
                            {
                            }
                            else
                            {
                                rightText  = (month + 1).ToString();
                                rightQuery = "?view=day&year=" + year + "&month=" + month + "&day=" + (day + 1).ToString();
                            }
                        }
                        startdate = new DateTime(year, month, day, 0, 0, 0);
                        enddate   = new DateTime(year, month, day, 23, 59, 59);
                        break;
                    }

                    default:
                    {
                        year  = DateTime.Now.Year;
                        month = DateTime.Now.Month;
                        day   = DateTime.Now.Day;

                        months = Stats.ByDay(StaticData.alerts, ref alerts, year, month, day);


                        xLabel     = year + " " + CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(month) + " " + day;
                        yLabel     = "%H";
                        middleText = day + " " + CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(month).Substring(0, 3) + " " + year;
                        downText   = month.ToString();
                        downQuery  = "?view=month&year=" + year + "&month=" + month;
                        if (day > 1)
                        {
                            leftText  = (day - 1).ToString();
                            leftQuery = "?view=day&year=" + year + "&month=" + month + "&day=" + (day - 1).ToString();
                        }
                        if (day < DateTime.DaysInMonth(year, month))
                        {
                            if (year == DateTime.Now.Year && month == DateTime.Now.Month && day <= DateTime.Now.Day)
                            {
                            }
                            else
                            {
                                rightText  = (month + 1).ToString();
                                rightQuery = "?view=day&year=" + year + "&month=" + month + "&day=" + (day + 1).ToString();
                            }
                        }
                        startdate = new DateTime(year, month, day, 0, 0, 0);
                        enddate   = new DateTime(year, month, day, 23, 59, 59);
                        break;
                    }
                    }
                }
                else
                {
                    year  = DateTime.Now.Year;
                    month = DateTime.Now.Month;
                    //day = DateTime.Now.Day;

                    months = Stats.ByMonth(StaticData.alerts, ref alerts, year, month);


                    xLabel     = year + " " + CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(month);
                    yLabel     = "%d";
                    middleText = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(month).Substring(0, 3) + " " + year;
                    int upday = StaticData.alerts.Where(x => x.time.Year == year && x.time.Month == month).Select(x => x.time.Day).DefaultIfEmpty().Max();
                    upText    = upday.ToString();
                    upQuery   = "?view=day&year=" + year + "&month=" + month + "&day=" + upday;
                    downText  = year.ToString();
                    downQuery = "?view=year&year=" + year;
                    if (month < 12)
                    {
                        if (year == DateTime.Now.Year && month >= DateTime.Now.Month)
                        {
                        }
                        else
                        {
                            rightText  = (month + 1).ToString();
                            rightQuery = "?view=month&year=" + year + "&month=" + (month + 1);
                        }
                    }
                    if (month > 1)
                    {
                        leftText  = (month - 1).ToString();
                        leftQuery = "?view=month&year=" + year + "&month=" + (month - 1);
                    }
                    startdate = new DateTime(year, month, 1);
                    enddate   = new DateTime(year, month, DateTime.DaysInMonth(year, month));
                }

                attackers = Stats.ByAttacker(alerts);
                targets   = Stats.ByTarget(alerts);
                timeline  = Stats.SignaturesInTime(alerts, year, month, day);
                if (alerts.Count == 0)
                {
                    noevents = true;
                }
                if (StaticData.alerts != null && StaticData.alerts.Count() > 0)
                {
                    noalerts = false;
                }
                alerts          = null;
                timelineStart   = "new Date('" + startdate.ToString("yyyy/MM/dd HH:mm:ss") + "')";
                timelineEnd     = "new Date('" + enddate.ToString("yyyy/MM/dd HH:mm:ss") + "')";
                timeFilterStart = startdate.ToString("MM/dd/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);
                timeFilterEnd   = enddate.ToString("MM/dd/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);

                GC.Collect(1, GCCollectionMode.Forced);
                GC.Collect(2, GCCollectionMode.Forced);
                GC.WaitForPendingFinalizers();
            }
            catch (Exception e)
            {
                error = "e.Message";
                return;
            }
        }