public static string Create(TraceTable traceTable)
        {
            var discoveryReport = new StringBuilder();
            foreach (var scan in traceTable)
            {
                discoveryReport.AppendLine(new string('-', 64));
                discoveryReport.AppendLine();
                discoveryReport.AppendLine(scan.Key.ToString());
                discoveryReport.AppendLine();
                discoveryReport.AppendLine(new string('-', 64));

                foreach (var mode in scan.Value)
                {
                    foreach (var targetFile in mode.Value)
                    {
                        discoveryReport.AppendLine();
                        discoveryReport.Append(targetFile.Key);
                        discoveryReport.AppendLine();
                        discoveryReport.AppendLine();
                        discoveryReport.Append(targetFile.Value.ToString().Indent());
                        discoveryReport.AppendLine();
                    }
                }
            }

            return discoveryReport.ToString();
        }
        public static string Create(TraceTable traceTable)
        {
            var discoveryReport = new StringBuilder();

            foreach (var scan in traceTable)
            {
                discoveryReport.AppendLine(new string('-', 64));
                discoveryReport.AppendLine();
                discoveryReport.AppendLine(scan.Key.ToString());
                discoveryReport.AppendLine();
                discoveryReport.AppendLine(new string('-', 64));

                foreach (var mode in scan.Value)
                {
                    foreach (var targetFile in mode.Value)
                    {
                        discoveryReport.AppendLine();
                        discoveryReport.Append(targetFile.Key);
                        discoveryReport.AppendLine();
                        discoveryReport.AppendLine();
                        discoveryReport.Append(targetFile.Value.ToString().Indent());
                        discoveryReport.AppendLine();
                    }
                }
            }

            return(discoveryReport.ToString());
        }
Ejemplo n.º 3
0
        static void ScanDirectory(DirectoryInfo AppDirectory, string RelativeAppPath)
        {
            var ignoreExtensions = new[]
            {
                "png",
                "jpg",
                "jpeg",
                "gif",
                "ico",
                "js",
                "css",
            };

            var urlDictionary = CreateUrlDictionary(RelativeAppPath, AppDirectory);

            var urlCollections = new[]
            {
                urlDictionary.Select(x => x.Key).ToList(),
                new List <string>()
            };

            var           traceTable     = new TraceTable();
            var           report         = new StringBuilder();
            var           coverageReport = new StringBuilder();
            var           map            = new ApplicationMap();
            var           alerts         = new ScanAlertCollection();
            int           requestCount   = 0;
            MessageDumper messageDumper  = null;

            if (Config.DumpMessages)
            {
                messageDumper = new MessageDumper(_reportWriter.ReportPath.FullName);
            }

            for (int urlCollectionIndex = 0; urlCollectionIndex < 2; urlCollectionIndex++)
            {
                foreach (ScanPluginBase plugin in Config.ScanPlugins)
                {
                    if (Config.CodeCoverageReport > 0)
                    {
                        ScanMetrics.Default.Annotator.Reset();
                        ScanMetrics.Default.Annotator.AnnotationTable = ScanMetrics.Default.PluginAnnotations[plugin.ToString()];
                    }

                    if (!urlCollections[urlCollectionIndex].Any())
                    {
                        continue;
                    }

                    ScannerCli.DisplayScanPlugin(plugin);

                    foreach (var remotePath in urlCollections[urlCollectionIndex])
                    {
                        ScannerCli.DisplayResourcePath(remotePath);

                        IEnumerable <IEnumerable <TracedFunctionCall> > calls = null;
                        if (urlCollectionIndex == 0)
                        {
                            var key = urlDictionary[remotePath];

                            if (Program.PageFieldTable.ContainsKey(key))
                            {
                                calls = Program.PageFieldTable[key]
                                        .Select(x => x.Value.Select(y => new TracedFunctionCall()
                                {
                                    Name            = x.Key,
                                    ParameterValues = new List <string>()
                                    {
                                        y
                                    }
                                }));
                            }
                        }

                        for (int i = 0; i < plugin.ModeCount; i++)
                        {
                            foreach (var useStaticAnalysisInputs in new[]
                            {
                                false,
                                true
                            })
                            {
                                var trace = new FileTrace();

                                if (useStaticAnalysisInputs && calls != null)
                                {
                                    if (!calls.Any(x => x.Any()))
                                    {
                                        continue;
                                    }

                                    foreach (var c in calls)
                                    {
                                        trace.Calls.AddRange(c);
                                    }
                                }

                                bool discoveredVars = true;

                                while (discoveredVars)
                                {
                                    var traceFile = new FileInfo(TraceFileName);

                                    IOHelper.TryAction(traceFile.Delete);

                                    var client = new TcpClient()
                                    {
                                        ReceiveTimeout = Config.Timeout,
                                        SendTimeout    = Config.Timeout
                                    };

                                    while (!client.Connected)
                                    {
                                        try
                                        {
                                            client.Connect(Config.Server, Config.Port);
                                        }
                                        catch (SocketException ex)
                                        {
                                            ScannerCli.DisplayError(ex.Message);

                                            Thread.Sleep(5000);
                                        }
                                    }

                                    client.LingerState = new LingerOption(true, 0);
                                    HttpResponse resp = null;
                                    string       req, respString = "";

                                    using (var stream = client.GetStream())
                                    {
                                        req = plugin.BuildRequest(i, remotePath, trace);

                                        if (Config.DumpMessages)
                                        {
                                            messageDumper.Dump(req, requestCount, MessageType.Request);
                                        }

                                        var stopwatch = new Stopwatch();
                                        stopwatch.Start();
                                        stream.WriteString(req);

                                        try
                                        {
                                            var sgs = trace.Calls
                                                      .Superglobals()
                                                      .Select(x => new { x.Name, Value = x.ParameterValues.Count > 0 ? x.ParameterValues[0] : null })
                                                      .Distinct();

                                            var discoveredVarCount = sgs.Count();
                                            var reader             = new HttpResponseReader(stream);
                                            resp = reader.Read();
                                            stopwatch.Stop();
                                            respString = resp.CompleteResponse;

                                            ScannerCli.DisplayResponse(
                                                resp,
                                                i,
                                                discoveredVarCount,
                                                stopwatch.ElapsedMilliseconds,
                                                resp.CompleteResponse.Length);
                                        }
                                        catch (SocketException)
                                        {
                                            ScannerCli.DisplayResponseError(respString);
                                        }
                                        catch (IOException)
                                        {
                                            ScannerCli.DisplayResponseError(respString);
                                        }
                                    }

                                    if (urlCollectionIndex == 0 && resp != null)
                                    {
                                        var abs = "http://" + Config.Server + remotePath;

                                        var urls = new UriScraper()
                                        {
                                            Regex = new Regex(@"[/.]" + Config.Server + @"($|/)", RegexOptions.IgnoreCase | RegexOptions.Compiled),
                                        }
                                        .Parse(resp.Body, abs)
                                        .Select(x => new Uri(x).LocalPath);

                                        foreach (var url in urls)
                                        {
                                            if (!ignoreExtensions.Any(x => url.ToLower().EndsWith("." + x)) &&
                                                !urlCollections[0].Contains(url) &&
                                                !urlCollections[1].Contains(url))
                                            {
                                                urlCollections[1].Add(url);

                                                ScannerCli.DisplayDiscoveredUrl(url);
                                            }
                                        }
                                    }

                                    client.Close();

                                    if (Config.DumpMessages)
                                    {
                                        messageDumper.Dump(respString, requestCount, MessageType.Response);
                                    }

                                    requestCount++;
                                    traceFile = new FileInfo(TraceFileName);
                                    FileTrace newTrace = null;

                                    IOHelper.TryAction(() =>
                                    {
                                        if (traceFile.Exists)
                                        {
                                            using (var reader = traceFile.OpenText())
                                                newTrace = FileTrace.Parse(reader);
                                        }
                                    });

                                    if (newTrace == null)
                                    {
                                        newTrace = new FileTrace();
                                    }

                                    newTrace.Request  = req;
                                    newTrace.Response = respString;
                                    newTrace.File     = remotePath;

                                    var alert = plugin.ScanTrace(newTrace);

                                    if (alert != null)
                                    {
                                        if (Config.BeepOnAlert)
                                        {
                                            Console.Beep();
                                        }

                                        ScannerCli.DisplayAlert(alert);

                                        alerts.Add(alert);
                                        report.Append(alert.ToString());
                                    }

                                    discoveredVars = false;

                                    foreach (TracedFunctionCall c in newTrace.Calls
                                             .Superglobals()
                                             .Where(x => x.ParameterValues.Any()))
                                    {
                                        var oldCalls = trace.Calls.Where(x =>
                                                                         x.Name == c.Name &&
                                                                         x.ParameterValues.SequenceEqual(c.ParameterValues));
                                        if (!oldCalls.Any())
                                        {
                                            discoveredVars = true;
                                            break;
                                        }
                                    }

                                    var orphanedInputs = trace.Calls
                                                         .Superglobals()
                                                         .Where(x => !newTrace.Calls
                                                                .Any(y => x.Name == y.Name && x.ParameterValues
                                                                     .SequenceEqual(y.ParameterValues)))
                                                         .ToArray();

                                    newTrace.Calls.AddRange(orphanedInputs);
                                    trace = newTrace;
                                }

                                var superglobals = trace.Calls.Superglobals();

                                map.AddTrace(trace);

                                if (Config.DiscoveryReport)
                                {
                                    if (!traceTable.ContainsKey(plugin))
                                    {
                                        traceTable.Add(plugin, new Dictionary <int, Dictionary <string, FileTrace> >());
                                    }

                                    if (!traceTable[plugin].ContainsKey(i))
                                    {
                                        traceTable[plugin].Add(i, new Dictionary <string, FileTrace>());
                                    }

                                    if (!traceTable[plugin][i].ContainsKey(trace.File))
                                    {
                                        traceTable[plugin][i].Add(trace.File, trace);
                                    }
                                    else
                                    {
                                        traceTable[plugin][i][trace.File] = trace;
                                    }
                                }
                            }
                        }
                    }

                    if (Config.CodeCoverageReport > 0 && urlCollectionIndex == 0)
                    {
                        Cli.WriteLine("Calculating code coverage...");
                        CodeCoverageTable coverage = null;

                        IOHelper.TryAction(() =>
                        {
                            var calculator = new CodeCoverageCalculator(
                                ScanMetrics.Default.Annotator.AnnotationFile,
                                ScanMetrics.Default.PluginAnnotations[plugin.ToString()]);
                            coverage = calculator.CalculateCoverage();
                        });

                        coverage.Plugin = plugin.ToString();
                        coverageReport.AppendLine(coverage.ToString() + "\r\n");
                    }

                    Cli.WriteLine();
                }
            }

            _reportWriter.Write("Vulnerability Report", report.ToString());
            _reportWriter.Write("Input Map Report", map.ToXml(), "xml");

            if (alerts.Any())
            {
                _reportWriter.Write("Vulnerability Report",
                                    alerts.ToXml(), "pxml");
            }

            if (Config.DiscoveryReport)
            {
                _reportWriter.Write("Scan Overview Report",
                                    DiscoveryReport.Create(traceTable));
            }

            if (Config.CodeCoverageReport > 0)
            {
                _reportWriter.Write("Code Coverage Report", coverageReport.ToString());
                var annotationXml = ScanMetrics.Default.PluginAnnotations.ToXml();

                var annotationFile = _reportWriter.Write(
                    "Annotation",
                    annotationXml,
                    "axml");

                Cli.WriteLine();
                var commenter = new CoverageCommenter(ScanMetrics.Default.PluginAnnotations);
                commenter.LoadTable(annotationFile);
                commenter.WriteCommentedFiles(_reportWriter.ReportPath.FullName);

                _reportWriter.ReportFiles.Add(
                    new ReportFile(
                        "Coverage Comments",
                        Path.Combine("Code Coverage", "index.html")));
            }
        }
 public void ProcessTraceFile()
 {
     try
     {
         // throttle execution based on semaphore
         Sem.WaitOne();
         if (!bCancel)
         {
             // This is so ugly but TraceFile reader initially sets to null first time it is used.  I don't know why.  Repeating to try again resolved.
             // I suspect a bug in the trace library, since there is no documented reason a valid trace file path should ever set the object state to null.
             // I think the first time it fails due to relevant aspects of library not being initialized in the process yet or something?
             // Subsequent tries appear to succed, resolving subtle bug where first file would just get skipped...
             // I had to do the same thing with TraceTable after it...  It now reliably loads all files after long frustrating investigation to find this root cause.
             while (true)
             {
                 tIn.InitializeAsReader(FileName);
                 if (tIn == null)
                 {
                     tIn  = new TraceFile();
                     tOut = new TraceTable();
                 }
                 else
                 {
                     break;
                 }
             }
             string tempTable = CurFile == 0 ? Table : "##" + Table + "_" + CurFile;
             while (true)
             {
                 try
                 {
                     tOut.InitializeAsWriter(tIn, cib, tempTable);
                     if (tOut == null)
                     {
                         tOut = new TraceTable();
                     }
                     else
                     {
                         break;
                     }
                 }
                 catch
                 {
                     tOut = new TraceTable();
                 }
             }
             SqlConnection conn = new SqlConnection(ConnStr);
             conn.Open();
             bool bFirstFile = false;
             if (String.IsNullOrEmpty(cols) || String.IsNullOrWhiteSpace(cols))
             {
                 // get column list from first trace file...
                 SetText("Retreiving column list from trace file " + FileName + ".");
                 string c = new SqlCommand("SELECT SUBSTRING((SELECT ', ' + QUOTENAME(COLUMN_NAME) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '" + Table + "' AND COLUMN_NAME <> 'RowNumber' ORDER BY ORDINAL_POSITION FOR XML path('')), 3, 200000);", conn).ExecuteScalar() as string;
                 object o = new object();
                 lock (o)
                 {
                     cols       = c;
                     bFirstFile = true;
                 }
                 Sem.Release(-1 + System.Environment.ProcessorCount * 2);  // We blocked everything until we got initial cols, now we release them all to run...
             }
             else
             {
                 string newCols = new SqlCommand("SELECT SUBSTRING((SELECT ', ' + QUOTENAME(COLUMN_NAME) FROM tempdb.INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '##" + Table + "_" + CurFile + "' AND COLUMN_NAME <> 'RowNumber' ORDER BY ORDINAL_POSITION FOR XML path('')), 3, 200000);", conn).ExecuteScalar() as string;
                 if (cols != newCols)
                 {
                     SetText("File " + FileName + " has mismatched columns from existing columns already defined by the first file found in the rollover trace series.  The columns defined in the current file are:\r\n" + newCols
                             + "\r\nThe columns defined in the first trace file encountered were:\r\n" + cols + "\r\nThe trace cannot be loaded and will be cancelled.  Try deleting non-matching file(s) to reload the actual contiguous rollover series.\r\n");
                     SetText("Columns not matched for file " + FileName + ".  Skipping this file from import.");
                     Sem.Release(1);
                     return;  // only happens if there is column mismatch between files - we won't read the whole file, just skip over...
                 }
             }
             conn.Close();
             if (!bCancel)
             {
                 try
                 {
                     while (!bCancel && tOut.Write())
                     {
                         if (RowCount++ % (384 * ((Environment.ProcessorCount > ASProfilerTraceImporterCmd.FileCount / 2) ? ASProfilerTraceImporterCmd.FileCount : Environment.ProcessorCount)) == 0)
                         {
                             global::ASProfilerTraceImporterCmd.ASProfilerTraceImporterCmd.UpdateRowCounts();
                         }
                     }
                 }
                 catch (SqlTraceException ste)
                 {
                     string s = ste.Message;
                 }
             }
             if (!bFirstFile && !bCancel)
             {
                 Sem.Release(1); // release this code for next thread waiting on the semaphore
             }
         }
     }
     catch (Exception e)
     {
         if (!bCancel)
         {
             SetText(e.ToString() + "\r\n\r\nException occurred while loading file " + FileName + ".\r\nStack:\r\n" + e.StackTrace + "\r\n\r\n" + e.Source);
             bCancel = true;
             Sem.Release(Environment.ProcessorCount * 2);
         }
     }
 }
 public TraceFileProcessor(int curFile, string fileName, string table, Semaphore sem, TraceFile tin, TraceTable tout)
 {
     CurFile = curFile; FileName = fileName; Table = table; Sem = sem; tIn = tin; tOut = tout;
 }
Ejemplo n.º 6
0
        void DoWork(object SSAS)
        {
            string      SSASserver             = (string)SSAS;
            TraceTable  _SQLDestTableWriter    = null;
            TraceServer _SSASSourceTraceServer = null;
            int         _RetryCounter          = 0;
            bool        bFirstLoop             = true;

            while (bFirstLoop || _RetryCounter < Properties.Settings.Default.RestartRetries)
            {
                bFirstLoop = false;
                try
                {
                    //Grab connection to SSAS
                    bool bSuccess = ConnectOlap(out _SSASSourceTraceServer, SSASserver);

                    if (bSuccess)
                    {
                        //Grab connection to SQL and connect it with the SSAS trace
                        bSuccess = ConnectSQL(ref _SSASSourceTraceServer, out _SQLDestTableWriter, SSASserver);

                        if (bSuccess)
                        {
                            _RetryCounter = 0;

                            while (_SQLDestTableWriter.Write())
                            {
                                if (_SQLDestTableWriter.IsClosed)
                                {
                                    throw new Exception("SQL connection closed unexpectedly.");
                                }
                                if (_SSASSourceTraceServer.IsClosed)
                                {
                                    throw new Exception("SSAS connection closed unexpectedly.");
                                }
                            }
                        }
                    }
                }

                catch (Exception ex)
                {
                    StringBuilder messageText = new StringBuilder();

                    messageText.Append(DateTime.Now.ToString() + ":  Error reading trace: " + ex.Message).AppendLine();
                    messageText.Append(ex.StackTrace).AppendLine();

                    while (ex.InnerException != null)
                    {
                        messageText.Append("INNER EXCEPTION: ");
                        messageText.Append(ex.InnerException.Message).AppendLine();
                        messageText.Append(ex.InnerException.StackTrace).AppendLine();

                        ex = ex.InnerException;
                    }

                    WriteLog(messageText.ToString());
                    EventLog.WriteEntry(this.ServiceName, messageText.ToString(), EventLogEntryType.Warning);
                }

                try
                {
                    _SSASSourceTraceServer.Stop();
                    _SSASSourceTraceServer.Close();
                }
                catch { }
                try
                {
                    _SQLDestTableWriter.Close();
                }
                catch { }


                _RetryCounter++;

                if (_RetryCounter < Properties.Settings.Default.RestartRetries)
                {
                    StringBuilder messageText2 = new StringBuilder();
                    messageText2.Append(DateTime.Now.ToString() + ":  Exception caught tracing server: " + SSASserver + ", retry " + _RetryCounter + " of " + Properties.Settings.Default.RestartRetries
                                        + ". Pausing for " + Properties.Settings.Default.RestartDelayMinutes + " minute(s) then restarting automatically"
                                        ).AppendLine();
                    WriteLog(messageText2.ToString());
                    EventLog.WriteEntry(this.ServiceName, messageText2.ToString(), EventLogEntryType.Warning);
                    System.Threading.Thread.Sleep(new TimeSpan(0, Properties.Settings.Default.RestartDelayMinutes, 0));
                }
                else
                {
                    WriteLog(DateTime.Now.ToString() + ":  Exceeded the number of allowed retries for server: " + SSASserver);
                }
            }

            //if this one trace exceeded the number of retries so stop the service and stop all traces
            Stop();
        }
Ejemplo n.º 7
0
        bool ConnectSQL(ref TraceServer traceServer, out TraceTable tableWriter, string SSASserver)
        {
            SqlConnectionInfo connInfo    = new SqlConnectionInfo(Properties.Settings.Default.SQLServer);
            StringBuilder     messageText = new StringBuilder();

            string _AppendInst = "_" + SSASserver;
            string _SQLTable;
            string _AppendDate;

            //Maintains legacy logic where by a server with single instance does not have any inst names appended.
            if (_NumInstance == 1)
            {
                _AppendInst = "";
            }
            //Append data to end of SQL table. Useful as an alternative to preserver SQL but data only survives 1 restart a day and you need cleanup logic in SQL Server
            if (Properties.Settings.Default.AppendDateToSQLTable)
            {
                _AppendDate = "_" + DateTime.Now.ToString("yyyyMMdd");
            }
            else
            {
                _AppendDate = "";
            }

            _SQLTable =
                Properties.Settings.Default.TraceTableName
                + _AppendInst
                + _AppendDate;

            if (Properties.Settings.Default.PreserveHistory)
            {
                PreserveSQLHistory(ref _SQLTable);
            }

            tableWriter = new TraceTable();

            try
            {
                connInfo.DatabaseName = Properties.Settings.Default.SQLServerDatabase;
                tableWriter.InitializeAsWriter(traceServer, connInfo, _SQLTable);

                messageText.Append(DateTime.Now.ToString() + ":  Created Analysis Server trace table: '" + _SQLTable + "' on SQL Server: '" + Properties.Settings.Default.SQLServer
                                   + "' in database: " + Properties.Settings.Default.SQLServerDatabase + "'");
                WriteLog(messageText.ToString());
                EventLog.WriteEntry(this.ServiceName, messageText.ToString(), EventLogEntryType.Information);
                return(true);
            }

            catch (Exception e)
            {
                messageText.Append(DateTime.Now.ToString() + ":  Cannot create Analysis Server trace table: '" + SSASserver + "'").AppendLine();
                messageText.Append(DateTime.Now.ToString() + ":  SQL Server Name: '" + Properties.Settings.Default.SQLServer + "'").AppendLine();
                messageText.Append(DateTime.Now.ToString() + ":  SQL Server Database : '" + Properties.Settings.Default.SQLServerDatabase + "'").AppendLine();
                messageText.Append(DateTime.Now.ToString() + ":  SQL Server Table : '" + _SQLTable + "'").AppendLine();
                messageText.Append(DateTime.Now.ToString() + ":  Error: " + e.Message).AppendLine();

                while (e.InnerException != null)
                {
                    messageText.Append("INNER EXCEPTION: ");
                    messageText.Append(e.InnerException.Message).AppendLine();
                    messageText.Append(e.InnerException.StackTrace.ToString()).AppendLine();

                    e = e.InnerException;
                }

                WriteLog(messageText.ToString());
                EventLog.WriteEntry(this.ServiceName, messageText.ToString(), EventLogEntryType.Error);

                return(false);
            }
        }
Ejemplo n.º 8
0
        private void butTrace_Click(object sender, RoutedEventArgs e)
        {
            // specify what to send (modifiers, fields, ...). Can be slow on complexe objects
            TraceDisplayFlags flags = TraceDisplayFlags.ShowModifiers |
                                      TraceDisplayFlags.ShowInheritedMembers |
                                      TraceDisplayFlags.ShowNonPublic |
                                      TraceDisplayFlags.ShowFields;

            if (ChkSendFunctions.IsChecked != null && (bool)ChkSendFunctions.IsChecked)
            {
                flags |= TraceDisplayFlags.ShowMethods;
            }


            //TTrace.Debug.SendObject("button1", button1);
            //button1.Width = button1.Width + 10;
            //button1.SetValue(Canvas.LeftProperty, (double)button1.GetValue(Canvas.LeftProperty) + 1);
            if (ChkSendProcessName.IsChecked != null)
            {
                TTrace.Options.SendProcessName = (bool)ChkSendProcessName.IsChecked;
            }
            string str = '\u2250' + "qwerty & @ € é ù è azerty" + '\u9999';

            // simple traces
            //--------------------------------------------
            TTrace.Debug.Send("Hello").Send("World"); // "World" is a sub trace of "Hello"

            // single separator
            TTrace.Debug.Send("---");

            // send traces with special font style (bold and Italic), color font size and font name
            // use System.Drawing.Color.ToArgb() (not supported in Silverlight) or (int)Helper.ToArgb(System.Windows.Media.Color) to specify Argb color
            TTrace.Debug.Send("Special font", "Symbol 12")
            .SetFontDetail(-1, false, true)                                                         // set whole line to italic
            .SetFontDetail(3, true, false, System.Drawing.Color.Red.ToArgb())                       // set col 3 (Left Msg)  to bold and Red
            .SetFontDetail(4, false, false, System.Drawing.Color.Green.ToArgb(), 12, "Symbol");     // set col 4 (Right Msg) to Green , font size 12 , Symbol
            TTrace.Debug.Send("Impact Italic")
            .SetFontDetail(3, false, true, System.Drawing.Color.BlueViolet.ToArgb(), 12, "Impact"); // Col3 (left msg), non bold, Italic , Blue-Violet , font 12 , Impact

            TTrace.Debug.Send("Special chars", "€ é ù è $ ");

            // The characters to encode:
            //    Latin Small Letter Z (U+007A)
            //    Latin Small Letter A (U+0061)
            //    Combining Breve (U+0306)
            //    Latin Small Letter AE With Acute (U+01FD)
            //    Greek Small Letter Beta (U+03B2)
            //    a high-surrogate value (U+D8FF)
            //    a low-surrogate value (U+DCFF)
            //char[] myChars = new char[] { 'z', 'a', '\u0306', '\u01FD', '\u03B2', '\uD8FF', '\uDCFF' };
            //TTrace.Debug.Send("Other Special chars", new StringBuilder().Append(myChars).ToString());  // note that myChars.ToString() return  "char[]"

            // double separator
            TTrace.Debug.Send("===");

            //TTrace.Options.SendThreadId = false ;
            //TTrace.Debug.Send("trace without thread id");
            //TTrace.Options.SendThreadId = true;

            //TTrace.Options.SendDate = true;
            //TTrace.Debug.Send("trace with date");
            //TTrace.Options.SendDate = false;

            // traces using Sendxxx method
            //--------------------------------------------
            // Use default display filter. (see TTrace.Options)

            TTrace.Debug.SendType("Object base type", typeof(Object));
            TTrace.Debug.SendType("My interface", typeof(IMyinterface));
            TTrace.Debug.SendObject("My const", TraceConst.CST_CREATE_MEMBER);
            TTrace.Debug.SendObject("My enum", _testClass.FieldDay);
            TTrace.Debug.SendCaller("SendCaller test", 0);
            TTrace.Debug.SendStack("Stack test", 0);
            TTrace.Debug.SendDump("SendDump test", "Unicode", Encoding.Unicode.GetBytes(str), 50);

            TTrace.Warning.SendType("SendType 'testClass'", _testClass.GetType());

            TTrace.Error.SendObject("SendObject 'testClass'", _testClass, flags);

            // traces using TraceNodeEx
            //--------------------------------------------
            TraceNodeEx node = new TraceNodeEx(null); //  TTrace.Debug

            node.LeftMsg  = "TraceNodeEx";
            node.RightMsg = str;
            node.AddFontDetail(3, false, false, System.Drawing.Color.Green.ToArgb());
            node.IconIndex = 8;
            node.Members.Add("My Members", "col2", "col3")
            .SetFontDetail(0, true)                                              // set first column to bold
            .SetFontDetail(1, false, false, System.Drawing.Color.Green.ToArgb()) // set second column to green
            .Add("Sub members")                                                  // add sub member node
            .SetFontDetail(0, false, true);                                      // set first column to Italic
            node.AddDump("ASCII", Encoding.ASCII.GetBytes(str), 50);             // 3F 61 7A          ..... 3F
            node.AddDump("UTF8", Encoding.UTF8.GetBytes(str), 50);
            node.AddDump("Unicode", Encoding.Unicode.GetBytes(str), 50);         // 50 22 61 00 7A 00 ..... 99 99
            node.AddStackTrace(0);
            node.AddCaller();
            TraceNode sendNode = node.Send();

            sendNode.ResendIconIndex(5); // change icon index after the node is send

            // XML sample using Send
            //--------------------------------------------
            TTrace.Debug.SendXml("xml", "<?xml version='1.0' ?><Data> Hello XML </Data>");

            // Image sample using Send
            //--------------------------------------------

            //TTrace.Debug.SendBitmap("Bitmap", Image1);

            // Text, image and XML together
            //--------------------------------------------
            node         = new TraceNodeEx(TTrace.Debug);
            node.LeftMsg = "Text, image and XML together";
            node.Members.Add("Text displayed in detail");
            //node.AddBitmap(Image1);
            node.AddXML("<?xml version='1.0' ?><Data> Xml in traceNodeEx </Data>");
            node.Send();

            // group of traces enabled / disabled
            //------------------------------------
            TraceNode groupTrace = new TraceNode(null, false); // dummy node not send to viewer

            groupTrace.IconIndex = 5;
            groupTrace.Enabled   = true;
            groupTrace.Send("GroupTrace traces 1"); // send to viewer
            groupTrace.Enabled = false;
            groupTrace.Send("GroupTrace traces 2"); // not send : group not enabled

            // generics
            //------------------------------------
            TTrace.Debug.SendType("typeof(Dictionary<,>)", typeof(Dictionary <,>), flags);                                  // open generic
            TTrace.Debug.SendType("typeof(Dictionary<Window, structTest>", typeof(Dictionary <Window, StructTest>), flags); // closed generic
            TTrace.Debug.SendObject("new Dictionary<Window, structTest>()", new Dictionary <Window, StructTest>(), flags);

            TTrace.Debug.SendType("typeof(templateTest<,>)", typeof(TemplateTest <,>), flags);
            TTrace.Debug.SendObject("new templateTest<Window, structTest>()", new TemplateTest <Window, StructTest>(), flags);


            // Display tables : use an object that implement : Array or IEnumerable or IDictionary or create a special table
            //--------------------------------------------------------------------------------------------------------------

            // 1) array of int
            int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 };
            int[] numbersB = { 1, 3, 5, 7, 8 };
            TTrace.Debug.SendTable("numbersA", numbersA);
            TTrace.Debug.SendTable("numbersB", numbersB);

            // Linq on array
            var pairs =
                from a in numbersA
                from b in numbersB
                where a < b
                select new { a, b };

            TTrace.Debug.SendTable("Linq query on series", pairs);

            // 2) array of FileInfo[]
            string        strTempPath = Path.GetTempPath();
            DirectoryInfo tempPath    = new DirectoryInfo(strTempPath);

            TTrace.Debug.SendTable("Files in temp path", tempPath.GetFiles());

            // Linq to array of FileInfo[]
            var linqToObjectQuery = from file in tempPath.GetFiles()
                                    where file.Length > 100
                                    orderby file.Length descending
                                    select new
            {
                file.Name,
                file.Length,
                file.LastWriteTime,
                file
            };

            TTrace.Debug.SendTable("Files having length>100 in temp path (Linq)", linqToObjectQuery);


            // 3) IDictionary : Hashtable
            Hashtable openWith = new Hashtable();

            openWith.Add("txt", "notepad.exe");
            openWith.Add("bmp", "paint.exe");
            openWith.Add("dib", "paint.exe");
            openWith.Add("rtf", "wordpad.exe");
            TTrace.Debug.SendTable("Hashtable", openWith);

            // 4) UnTyped collection : Stack
            Stack windowStack = new Stack(5);

            windowStack.Push(this);
            windowStack.Push(this);
            windowStack.Push(this);
            TTrace.Debug.SendTable("Stack ", windowStack);

            // 5) Typed collection (implement ICollection)
            Collection <Window> windowsCollection = new Collection <Window>();

            for (int c = 0; c < 500; c++)
            {
                windowsCollection.Add(this);
            }
            TTrace.Debug.SendTable("window Collection", windowsCollection);

            Collection <int> intCollection = new Collection <int>();

            for (int c = 0; c < 500; c++)
            {
                intCollection.Add(c);
            }
            TTrace.Debug.SendTable("int Collection", intCollection);

            // 6) create manually a table
            TraceTable table = new TraceTable();

            // add titles. Individual columns titles can be added or multiple columns , separated by tabs
            table.AddColumnTitle("colA");                 // first column title
            table.AddColumnTitle("colB");                 // second column title
            table.AddColumnTitle("title column C\tcolD"); // other columns title (tab separated)

            // add first line. Individual columns data can be added or multiple columns , separated by tabs
            table.AddRow();
            table.AddRowData("a");                                        // add first col
            table.AddRowData("b" + "\t" + "c" + "\t" + "d" + "\t" + "e"); // then add other columns (tab separated)

            // add second line
            table.AddRow();
            table.AddRowData("aa" + "\t" + "data second column" + "\t" + "cc" + "\t" + "dd" + "\t" + "ee"); // add all columns data in a single step (tab separated)

            // finally send the table
            TTrace.Debug.SendTable("Mytable", table);


            // ensure all traces are send to the viewer
            TTrace.Flush();
        }
Ejemplo n.º 9
0
        private void butTrace_Click(object sender, EventArgs e)
        {
            TTrace.Options.SendProcessName = chkSendProcessName.Checked;
            string str = '\u2250' + "qwerty é ù è azerty" + '\u9999';

            // simple traces
            //--------------------------------------------
            TTrace.Debug.Send("Hello").Send("World");  // "World" is a sub trace of "Hello"

            // single separator
            TTrace.Debug.Send("---");

            // send traces with special font style (bold and Italic), color font size and font name
            TTrace.Debug.Send("Special font", "Symbol 12")
            .SetFontDetail(-1, false, true)                                           // set whole line to italic
            .SetFontDetail(3, true, false, Color.Red.ToArgb())                        // set col 3 (Left Msg)  to bold and Red
            .SetFontDetail(4, false, false, Color.Green.ToArgb(), 12, "Symbol");      // set col 4 (Right Msg) to Green , font size 12 , Symbol
            TTrace.Debug.Send("Impact Italic")
            .SetFontDetail(3, false, true, Color.BlueViolet.ToArgb(), 12, "Impact");  // Col3 (left msg), non bold, Italic , Blue-Violet , font 12 , Impact

            // double separator
            TTrace.Debug.Send("===");

            //TTrace.Options.SendThreadId = false ;
            //TTrace.Debug.Send("trace without thread id");
            //TTrace.Options.SendThreadId = true;

            //TTrace.Options.SendDate = true;
            //TTrace.Debug.Send("trace with date");
            //TTrace.Options.SendDate = false;

            // traces using Sendxxx method
            //--------------------------------------------
            // Use default display filter. (see TTrace.Options)

            TTrace.Debug.SendType("Object base type", typeof(Object));
            TTrace.Debug.SendType("My interface", typeof(Myinterface));
            TTrace.Debug.SendObject("My const", TraceConst.CST_CREATE_MEMBER);
            TTrace.Debug.SendObject("My enum", testClass.fieldDay);
            TTrace.Debug.SendCaller("SendCaller test", 0);
            TTrace.Debug.SendStack("Stack test", 0);
            TTrace.Debug.SendDump("SendDump test", "Unicode", Encoding.Unicode.GetBytes(str), 50);

            TTrace.Warning.SendType("SendType 'testClass'", testClass.GetType());

            // specify what to send (modifiers, fields, ...). Can be slow on complexe objects
            TraceDisplayFlags flags = TraceDisplayFlags.ShowModifiers |
                                      TraceDisplayFlags.ShowInheritedMembers |
                                      TraceDisplayFlags.ShowNonPublic |
                                      TraceDisplayFlags.ShowFields;

            if (chkSendFunctions.Checked)
            {
                flags |= TraceDisplayFlags.ShowMethods;
            }
            TTrace.Error.SendObject("SendObject 'testClass'", testClass, flags);

            // traces using TraceNodeEx
            //--------------------------------------------
            TraceNodeEx node = new TraceNodeEx(null);  //  TTrace.Debug

            node.LeftMsg  = "TraceNodeEx";
            node.RightMsg = "demo";
            node.AddFontDetail(3, false, false, Color.Green.ToArgb());
            node.IconIndex = 8;
            node.Members.Add("My Members", "col2", "col3")
            .SetFontDetail(0, true)                                      // set first column to bold
            .SetFontDetail(1, false, false, Color.Green.ToArgb())        // set second column to green
            .Add("Sub members")                                          // add sub member node
            .SetFontDetail(0, false, true);                              // set first column to Italic
            node.AddDump("ASCII", Encoding.ASCII.GetBytes(str), 50);     // 3F 61 7A          ..... 3F
            node.AddDump("UTF8", Encoding.UTF8.GetBytes(str), 50);
            node.AddDump("Unicode", Encoding.Unicode.GetBytes(str), 50); // 50 22 61 00 7A 00 ..... 99 99
            node.AddStackTrace(0);
            node.AddCaller();
            TraceNode sendNode = node.Send();

            sendNode.ResendIconIndex(5);  // change icon index after the node is send

            // XML sample using Send
            //--------------------------------------------
            TTrace.Debug.SendXml("xml", "<?xml version='1.0' ?><Data> Hello XML </Data>");

            // Image sample using Send
            //--------------------------------------------
            TTrace.Debug.SendBitmap("Bitmap", pictureBox1.Image);

            // Text, image and XML together
            //--------------------------------------------
            node         = new TraceNodeEx(TTrace.Debug);
            node.LeftMsg = "Text, image and XML together";
            node.Members.Add("Text displayed in detail");
            node.AddBitmap(pictureBox1.Image);
            node.AddXML("<?xml version='1.0' ?><Data> Xml in traceNodeEx </Data>");
            node.Send();

            // send table detail
            //--------------------------------------------

            // create the table
            TraceTable table = new TraceTable();

            // add titles. Individual columns titles can be added or multiple columns , separated by tabs
            table.AddColumnTitle("colA");                 // first column title
            table.AddColumnTitle("colB");                 // second column title
            table.AddColumnTitle("title column C\tcolD"); // other columns title (tab separated)

            // add first line. Individual columns data can be added or multiple columns , separated by tabs
            table.AddRow();
            table.AddRowData("a");                                        // add first col
            table.AddRowData("b" + "\t" + "c" + "\t" + "d" + "\t" + "e"); // then add other columns (tab separated)

            // add second line
            table.AddRow();
            table.AddRowData("aa" + "\t" + "data second column" + "\t" + "cc" + "\t" + "dd" + "\t" + "ee");  // add all columns data in a single step (tab separated)

            // finally send the table
            TTrace.Debug.SendTable("Mytable", table);

            // ensure all traces are send to the viewer
            TTrace.Flush();
        }
Ejemplo n.º 10
0
        //--------------------------------------------------------
        private void butTrace_Click(object sender, EventArgs e)
        {
            TTrace.Options.SendProcessName = chkSendProcessName.Checked;
               string str = '\u2250' + "qwerty & @ € é ù è azerty" + '\u9999';

               // simple traces
               //--------------------------------------------
               TTrace.Debug.Send("Hello").Send("World");  // "World" is a sub trace of "Hello"

               // single separator
               TTrace.Debug.Send("---");

               // send traces with special font style (bold and Italic), color font size and font name
               TTrace.Debug.Send("Special font", "Symbol 12")
               .SetFontDetail(-1, false, true)                                        // set whole line to italic
               .SetFontDetail(3, true, false, Color.Red.ToArgb())                     // set col 3 (Left Msg)  to bold and Red
               .SetFontDetail(4, false, false, Color.Green.ToArgb(), 12, "Symbol");   // set col 4 (Right Msg) to Green , font size 12 , Symbol
               TTrace.Debug.Send("Impact Italic")
               .SetFontDetail(3, false, true, Color.BlueViolet.ToArgb(), 12, "Impact");     // Col3 (left msg), non bold, Italic , Blue-Violet , font 12 , Impact

               TTrace.Debug.Send("Special chars", "€ é ù è $ ");

               // The characters to encode:
               //    Latin Small Letter Z (U+007A)
               //    Latin Small Letter A (U+0061)
               //    Combining Breve (U+0306)
               //    Latin Small Letter AE With Acute (U+01FD)
               //    Greek Small Letter Beta (U+03B2)
               //    a high-surrogate value (U+D8FF)
               //    a low-surrogate value (U+DCFF)
               //char[] myChars = new char[] { 'z', 'a', '\u0306', '\u01FD', '\u03B2', '\uD8FF', '\uDCFF' };
               //TTrace.Debug.Send("Other Special chars", new StringBuilder().Append(myChars).ToString());  // myChars.ToString() return  "char[]"

               // double separator
               TTrace.Debug.Send("===");

               //TTrace.Options.SendThreadId = false ;
               //TTrace.Debug.Send("trace without thread id");
               //TTrace.Options.SendThreadId = true;

               //TTrace.Options.SendDate = true;
               //TTrace.Debug.Send("trace with date");
               //TTrace.Options.SendDate = false;

               // traces using Sendxxx method
               //--------------------------------------------
               // Use default display filter. (see TTrace.Options)

               TTrace.Debug.SendType("Object base type", typeof(Object));
               TTrace.Debug.SendType("My interface", typeof(Myinterface));
               TTrace.Debug.SendObject("My const", TraceConst.CST_CREATE_MEMBER);
               TTrace.Debug.SendObject("My enum", testClass.fieldDay);
               TTrace.Debug.SendCaller("SendCaller test", 0);
               TTrace.Debug.SendStack("Stack test", 0);
               TTrace.Debug.SendDump("SendDump test", "Unicode", Encoding.Unicode.GetBytes(str), 50);

               TTrace.Warning.SendType("SendType 'testClass'", testClass.GetType());

            // specify what to send (modifiers, fields, ...). Can be slow on complexe objects
               TraceDisplayFlags flags = TraceDisplayFlags.ShowModifiers |
                                      TraceDisplayFlags.ShowInheritedMembers |
                                      TraceDisplayFlags.ShowNonPublic |
                                      TraceDisplayFlags.ShowFields;

               if (chkSendFunctions.Checked)
              flags |= TraceDisplayFlags.ShowMethods;
               TTrace.Error.SendObject("SendObject 'testClass'", testClass, flags);

               // traces using TraceNodeEx
               //--------------------------------------------
               TraceNodeEx node = new TraceNodeEx(null);  //  TTrace.Debug
               node.LeftMsg = "TraceNodeEx";
               node.RightMsg = str;
               node.AddFontDetail(3, false, false, Color.Green.ToArgb());
               node.IconIndex = 8;
               node.Members.Add("My Members", "col2", "col3")
              .SetFontDetail(0, true)                                 // set first column to bold
              .SetFontDetail(1, false, false, Color.Green.ToArgb())   // set second column to green
              .Add("Sub members")                                     // add sub member node
                 .SetFontDetail(0, false, true);                      // set first column to Italic
               node.AddDump("ASCII", Encoding.ASCII.GetBytes(str), 50);   // 3F 61 7A          ..... 3F
               node.AddDump("UTF8", Encoding.UTF8.GetBytes(str), 50);
               node.AddDump("Unicode", Encoding.Unicode.GetBytes(str), 50); // 50 22 61 00 7A 00 ..... 99 99
               node.AddStackTrace(0);
               node.AddCaller();
               TraceNode sendNode = node.Send();
               sendNode.ResendIconIndex(5);  // change icon index after the node is send

               // XML sample using Send
               //--------------------------------------------
               TTrace.Debug.SendXml("xml", "<?xml version='1.0' ?><Data> Hello XML </Data>");

               // Image sample using Send
               //--------------------------------------------
               TTrace.Debug.SendBitmap("Bitmap", pictureBox1.Image);

               // Text, image and XML together
               //--------------------------------------------
               node = new TraceNodeEx(TTrace.Debug);
               node.LeftMsg = "Text, image and XML together";
               node.Members.Add("Text displayed in detail");
               node.AddBitmap(pictureBox1.Image);
               node.AddXML("<?xml version='1.0' ?><Data> Xml in traceNodeEx </Data>");
               node.Send();

               // send table detail
               //--------------------------------------------

               // create the table
               TraceTable table = new TraceTable();

               // add titles. Individual columns titles can be added or multiple columns , separated by tabs
               table.AddColumnTitle("colA");          // first column title
               table.AddColumnTitle("colB");          // second column title
               table.AddColumnTitle("title column C\tcolD");  // other columns title (tab separated)

               // add first line. Individual columns data can be added or multiple columns , separated by tabs
               table.AddRow();
               table.AddRowData("a");                           // add first col
               table.AddRowData("b" + "\t" + "c" + "\t" + "d" + "\t" + "e");            // then add other columns (tab separated)

               // add second line
               table.AddRow();
               table.AddRowData("aa" + "\t" + "data second column" + "\t" + "cc" + "\t" + "dd" + "\t" + "ee");  // add all columns data in a single step (tab separated)

               // finally send the table
               TTrace.Debug.SendTable("Mytable", table);

               ParsedObjectList objList = new ParsedObjectList() ;
               objList.Add (testClass) ;
               objList.Add (test2) ;
               TTrace.Debug.SendTable("Generic table",objList );

               List<int> intCollection = new List<int>();
               for (int c = 0; c < 500; c++)
              intCollection.Add(c);
               TTrace.Debug.SendTable("int Collection", intCollection);

               // group of traces enabled / disabled
               TraceNode databinding = new TraceNode(null, false);
               databinding.IconIndex = 5;

               databinding.Enabled = true;
               databinding.Send("databing traces 1");
               databinding.Enabled = false;
               databinding.Send("databing traces 2");

               // ensure all traces are send to the viewer
               TTrace.Flush();
        }
Ejemplo n.º 11
0
        static void ScanDirectory(DirectoryInfo AppDirectory, string RelativeAppPath)
        {
            var ignoreExtensions = new[]
            {
                "png",
                "jpg",
                "jpeg",
                "gif",
                "ico",
                "js",
                "css",
            };

            var urlDictionary = CreateUrlDictionary(RelativeAppPath, AppDirectory);

            var urlCollections = new[]
            {
                urlDictionary.Select(x => x.Key).ToList(),
                new List<string>()
            };

            var traceTable = new TraceTable();
            var report = new StringBuilder();
            var coverageReport = new StringBuilder();
            var map = new ApplicationMap();
            var alerts = new ScanAlertCollection();
            int requestCount = 0;
            MessageDumper messageDumper = null;

            if (Config.DumpMessages)
            {
                messageDumper = new MessageDumper(_reportWriter.ReportPath.FullName);
            }

            for (int urlCollectionIndex = 0; urlCollectionIndex < 2; urlCollectionIndex++)
                foreach (ScanPluginBase plugin in Config.ScanPlugins)
                {
                    if (Config.CodeCoverageReport > 0)
                    {
                        ScanMetrics.Default.Annotator.Reset();
                        ScanMetrics.Default.Annotator.AnnotationTable = ScanMetrics.Default.PluginAnnotations[plugin.ToString()];
                    }

                    if (!urlCollections[urlCollectionIndex].Any())
                        continue;

                    ScannerCli.DisplayScanPlugin(plugin);

                    foreach (var remotePath in urlCollections[urlCollectionIndex])
                    {
                        ScannerCli.DisplayResourcePath(remotePath);

                        IEnumerable<IEnumerable<TracedFunctionCall>> calls = null;
                        if (urlCollectionIndex == 0)
                        {
                            var key = urlDictionary[remotePath];

                            if (Program.PageFieldTable.ContainsKey(key))
                                calls = Program.PageFieldTable[key]
                                    .Select(x => x.Value.Select(y => new TracedFunctionCall()
                                    {
                                        Name = x.Key,
                                        ParameterValues = new List<string>() { y }
                                    }));
                        }

                        for (int i = 0; i < plugin.ModeCount; i++)
                        {
                            foreach (var useStaticAnalysisInputs in new[]
                        {
                            false,
                            true
                        })
                            {
                                var trace = new FileTrace();

                                if (useStaticAnalysisInputs && calls != null)
                                {
                                    if (!calls.Any(x => x.Any()))
                                        continue;

                                    foreach (var c in calls)
                                        trace.Calls.AddRange(c);
                                }

                                bool discoveredVars = true;

                                while (discoveredVars)
                                {
                                    var traceFile = new FileInfo(TraceFileName);

                                    IOHelper.TryAction(traceFile.Delete);

                                    var client = new TcpClient()
                                    {
                                        ReceiveTimeout = Config.Timeout,
                                        SendTimeout = Config.Timeout
                                    };

                                    while (!client.Connected)
                                        try
                                        {
                                            client.Connect(Config.Server, Config.Port);
                                        }
                                        catch (SocketException ex)
                                        {
                                            ScannerCli.DisplayError(ex.Message);

                                            Thread.Sleep(5000);
                                        }

                                    client.LingerState = new LingerOption(true, 0);
                                    HttpResponse resp = null;
                                    string req, respString = "";

                                    using (var stream = client.GetStream())
                                    {
                                        req = plugin.BuildRequest(i, remotePath, trace);

                                        if (Config.DumpMessages)
                                        {
                                            messageDumper.Dump(req, requestCount, MessageType.Request);
                                        }

                                        var stopwatch = new Stopwatch();
                                        stopwatch.Start();
                                        stream.WriteString(req);

                                        try
                                        {
                                            var sgs = trace.Calls
                                                .Superglobals()
                                                .Select(x => new { x.Name, Value = x.ParameterValues.Count > 0 ? x.ParameterValues[0] : null })
                                                .Distinct();

                                            var discoveredVarCount = sgs.Count();
                                            var reader = new HttpResponseReader(stream);
                                            resp = reader.Read();
                                            stopwatch.Stop();
                                            respString = resp.CompleteResponse;

                                            ScannerCli.DisplayResponse(
                                                resp,
                                                i,
                                                discoveredVarCount,
                                                stopwatch.ElapsedMilliseconds,
                                                resp.CompleteResponse.Length);
                                        }
                                        catch (SocketException)
                                        {
                                            ScannerCli.DisplayResponseError(respString);
                                        }
                                        catch (IOException)
                                        {
                                            ScannerCli.DisplayResponseError(respString);
                                        }
                                    }

                                    if (urlCollectionIndex == 0 && resp != null)
                                    {
                                        var abs = "http://" + Config.Server + remotePath;

                                        var urls = new UriScraper()
                                        {
                                            Regex = new Regex(@"[/.]" + Config.Server + @"($|/)", RegexOptions.IgnoreCase | RegexOptions.Compiled),
                                        }
                                        .Parse(resp.Body, abs)
                                        .Select(x => new Uri(x).LocalPath);

                                        foreach (var url in urls)
                                        {
                                            if (!ignoreExtensions.Any(x => url.ToLower().EndsWith("." + x)) &&
                                                !urlCollections[0].Contains(url) &&
                                                !urlCollections[1].Contains(url))
                                            {
                                                urlCollections[1].Add(url);

                                                ScannerCli.DisplayDiscoveredUrl(url);
                                            }
                                        }
                                    }

                                    client.Close();

                                    if (Config.DumpMessages)
                                    {
                                        messageDumper.Dump(respString, requestCount, MessageType.Response);
                                    }

                                    requestCount++;
                                    traceFile = new FileInfo(TraceFileName);
                                    FileTrace newTrace = null;

                                    IOHelper.TryAction(() =>
                                    {
                                        if (traceFile.Exists)
                                            using (var reader = traceFile.OpenText())
                                                newTrace = FileTrace.Parse(reader);
                                    });

                                    if (newTrace == null)
                                    {
                                        newTrace = new FileTrace();
                                    }

                                    newTrace.Request = req;
                                    newTrace.Response = respString;
                                    newTrace.File = remotePath;

                                    var alert = plugin.ScanTrace(newTrace);

                                    if (alert != null)
                                    {
                                        if (Config.BeepOnAlert)
                                            Console.Beep();

                                        ScannerCli.DisplayAlert(alert);

                                        alerts.Add(alert);
                                        report.Append(alert.ToString());
                                    }

                                    discoveredVars = false;

                                    foreach (TracedFunctionCall c in newTrace.Calls
                                        .Superglobals()
                                        .Where(x => x.ParameterValues.Any()))
                                    {
                                        var oldCalls = trace.Calls.Where(x =>
                                            x.Name == c.Name &&
                                            x.ParameterValues.SequenceEqual(c.ParameterValues));
                                        if (!oldCalls.Any())
                                        {
                                            discoveredVars = true;
                                            break;
                                        }
                                    }

                                    var orphanedInputs = trace.Calls
                                        .Superglobals()
                                        .Where(x => !newTrace.Calls
                                            .Any(y => x.Name == y.Name && x.ParameterValues
                                                .SequenceEqual(y.ParameterValues)))
                                        .ToArray();

                                    newTrace.Calls.AddRange(orphanedInputs);
                                    trace = newTrace;
                                }

                                var superglobals = trace.Calls.Superglobals();

                                map.AddTrace(trace);

                                if (Config.DiscoveryReport)
                                {
                                    if (!traceTable.ContainsKey(plugin))
                                    {
                                        traceTable.Add(plugin, new Dictionary<int, Dictionary<string, FileTrace>>());
                                    }

                                    if (!traceTable[plugin].ContainsKey(i))
                                    {
                                        traceTable[plugin].Add(i, new Dictionary<string, FileTrace>());
                                    }

                                    if (!traceTable[plugin][i].ContainsKey(trace.File))
                                    {
                                        traceTable[plugin][i].Add(trace.File, trace);
                                    }
                                    else
                                    {
                                        traceTable[plugin][i][trace.File] = trace;
                                    }
                                }
                            }
                        }
                    }

                    if (Config.CodeCoverageReport > 0 && urlCollectionIndex == 0)
                    {
                        Cli.WriteLine("Calculating code coverage...");
                        CodeCoverageTable coverage = null;

                        IOHelper.TryAction(() =>
                        {
                            var calculator = new CodeCoverageCalculator(
                                ScanMetrics.Default.Annotator.AnnotationFile,
                                ScanMetrics.Default.PluginAnnotations[plugin.ToString()]);
                            coverage = calculator.CalculateCoverage();
                        });

                        coverage.Plugin = plugin.ToString();
                        coverageReport.AppendLine(coverage.ToString() + "\r\n");
                    }

                    Cli.WriteLine();
                }

            _reportWriter.Write("Vulnerability Report", report.ToString());
            _reportWriter.Write("Input Map Report", map.ToXml(), "xml");

            if (alerts.Any())
            {
                _reportWriter.Write("Vulnerability Report",
                    alerts.ToXml(), "pxml");
            }

            if (Config.DiscoveryReport)
            {
                _reportWriter.Write("Scan Overview Report",
                    DiscoveryReport.Create(traceTable));
            }

            if (Config.CodeCoverageReport > 0)
            {
                _reportWriter.Write("Code Coverage Report", coverageReport.ToString());
                var annotationXml = ScanMetrics.Default.PluginAnnotations.ToXml();

                var annotationFile = _reportWriter.Write(
                    "Annotation",
                    annotationXml,
                    "axml");

                Cli.WriteLine();
                var commenter = new CoverageCommenter(ScanMetrics.Default.PluginAnnotations);
                commenter.LoadTable(annotationFile);
                commenter.WriteCommentedFiles(_reportWriter.ReportPath.FullName);

                _reportWriter.ReportFiles.Add(
                    new ReportFile(
                        "Coverage Comments",
                        Path.Combine("Code Coverage", "index.html")));
            }
        }
Ejemplo n.º 12
0
        //------------------------------------------------------------------------------

        // send to default : "127.0.0.1" on port 4502
        private void butTrace_Click(object sender, RoutedEventArgs e)
        {
            //TTrace.Debug.SendObject("button1", button1);
            //button1.Width = button1.Width + 10;
            //button1.SetValue(Canvas.LeftProperty, (double)button1.GetValue(Canvas.LeftProperty) + 1);
            TTrace.Options.SendProcessName = (bool)chkSendProcessName.IsChecked;
            string str = '\u2250' + "qwerty & @ € é ù è azerty" + '\u9999';

            // simple traces
            //--------------------------------------------
            TTrace.Debug.Send("Hello").Send("World"); // "World" is a sub trace of "Hello"

            // single separator
            TTrace.Debug.Send("---");

            // send traces with special font style (bold and Italic), color font size and font name
            TTrace.Debug.Send("Special font", "Symbol 12")
            .SetFontDetail(-1, false, true)                                                     // set whole line to italic
            .SetFontDetail(3, true, false, (int)Helper.ToArgb(Colors.Red))                      // set col 3 (Left Msg)  to bold and Red
            .SetFontDetail(4, false, false, (int)Helper.ToArgb(Colors.Green), 12, "Symbol");    // set col 4 (Right Msg) to Green , font size 12 , Symbol
            TTrace.Debug.Send("Impact Italic")
            .SetFontDetail(3, false, true, (int)Helper.ToArgb(Colors.Orange), 12, "Impact");    // Col3 (left msg), non bold, Italic , Orange , font 12 , Impact

            TTrace.Debug.Send("Special chars", "€ é ù è $ ");

            // The characters to encode:
            //    Latin Small Letter Z (U+007A)
            //    Latin Small Letter A (U+0061)
            //    Combining Breve (U+0306)
            //    Latin Small Letter AE With Acute (U+01FD)
            //    Greek Small Letter Beta (U+03B2)
            //    a high-surrogate value (U+D8FF)
            //    a low-surrogate value (U+DCFF)
            //char[] myChars = new char[] { 'z', 'a', '\u0306', '\u01FD', '\u03B2', '\uD8FF', '\uDCFF' };
            //TTrace.Debug.Send("Other Special chars", new StringBuilder().Append(myChars).ToString());  // myChars.ToString() return  "char[]"

            // double separator
            TTrace.Debug.Send("===");

            //TTrace.Options.SendThreadId = false ;
            //TTrace.Debug.Send("trace without thread id");
            //TTrace.Options.SendThreadId = true;

            //TTrace.Options.SendDate = true;
            //TTrace.Debug.Send("trace with date");
            //TTrace.Options.SendDate = false;

            // traces using Sendxxx method
            //--------------------------------------------
            // Use default display filter. (see TTrace.Options)

            TTrace.Debug.SendType("Object base type", typeof(Object));
            TTrace.Debug.SendType("My interface", typeof(Myinterface));
            TTrace.Debug.SendObject("My const", TraceConst.CST_CREATE_MEMBER);
            TTrace.Debug.SendObject("My enum", testClass.fieldDay);
            TTrace.Debug.SendCaller("SendCaller test", 0);
            TTrace.Debug.SendStack("Stack test", 0);
            TTrace.Debug.SendDump("SendDump test", "Unicode", Encoding.Unicode.GetBytes(str), 50);

            TTrace.Warning.SendType("SendType 'testClass'", testClass.GetType());

            // specify what to send (modifiers, fields, ...). Can be slow on complexe objects
            TraceDisplayFlags flags = TraceDisplayFlags.ShowModifiers |
                                      TraceDisplayFlags.ShowInheritedMembers |
                                      TraceDisplayFlags.ShowNonPublic |
                                      TraceDisplayFlags.ShowFields;

            if ((bool)chkSendFunctions.IsChecked)
            {
                flags |= TraceDisplayFlags.ShowMethods;
            }
            TTrace.Error.SendObject("SendObject 'testClass'", testClass, flags);

            // traces using TraceNodeEx
            //--------------------------------------------
            TraceNodeEx node = new TraceNodeEx(null); //  TTrace.Debug

            node.LeftMsg  = "TraceNodeEx";
            node.RightMsg = str;
            node.AddFontDetail(3, false, false, (int)Helper.ToArgb(Colors.Green));
            node.IconIndex = 8;
            node.Members.Add("My Members", "col2", "col3")
            .SetFontDetail(0, true)                                                        // set first column to bold
            .SetFontDetail(1, false, false, (int)Helper.ToArgb(Colors.Green))              // set second column to green
            .Add("Sub members")                                                            // add sub member node
            .SetFontDetail(0, false, true);                                                // set first column to Italic
            node.AddDump("BigEndianUnicode", Encoding.BigEndianUnicode.GetBytes(str), 50); // 3F 61 7A          ..... 3F
            node.AddDump("UTF8", Encoding.UTF8.GetBytes(str), 50);
            node.AddDump("Unicode", Encoding.Unicode.GetBytes(str), 50);                   // 50 22 61 00 7A 00 ..... 99 99
            node.AddStackTrace(0);
            node.AddCaller();
            TraceNode sendNode = node.Send();

            sendNode.ResendIconIndex(5); // change icon index after the node is send

            // XML sample using Send
            //--------------------------------------------
            TTrace.Debug.SendXml("xml", "<?xml version='1.0' ?><Data> Hello XML </Data>");

            // Image sample using Send
            //--------------------------------------------

            // currently not possibe in silverlight 2 :
            // - No way to read the Image content
            // - BmpBitmapEncoder is not supported
            //TTrace.Debug.SendBitmap("Bitmap", image1);

            // Text and XML together
            //--------------------------------------------
            node         = new TraceNodeEx(TTrace.Debug);
            node.LeftMsg = "Text and XML together";
            node.Members.Add("Text displayed in detail");
            //node.AddBitmap(image1); // currently not possibe in silverlight 2
            node.AddXML("<?xml version='1.0' ?><Data> Xml in traceNodeEx </Data>");
            node.Send();

            // send table detail
            //--------------------------------------------

            // create the table
            TraceTable table = new TraceTable();

            // add titles. Individual columns titles can be added or multiple columns , separated by tabs
            table.AddColumnTitle("colA");                 // first column title
            table.AddColumnTitle("colB");                 // second column title
            table.AddColumnTitle("title column C\tcolD"); // other columns title (tab separated)

            // add first line. Individual columns data can be added or multiple columns , separated by tabs
            table.AddRow();
            table.AddRowData("a");                                        // add first col
            table.AddRowData("b" + "\t" + "c" + "\t" + "d" + "\t" + "e"); // then add other columns (tab separated)

            // add second line
            table.AddRow();
            table.AddRowData("aa" + "\t" + "data second column" + "\t" + "cc" + "\t" + "dd" + "\t" + "ee"); // add all columns data in a single step (tab separated)

            // finally send the table
            TTrace.Debug.SendTable("Mytable", table);

            // group of traces enabled / disabled
            TraceNode GroupTrace = new TraceNode(null, false);

            GroupTrace.IconIndex = 5;

            GroupTrace.Enabled = true;
            GroupTrace.Send("GroupTrace traces 1"); // send to viewer
            GroupTrace.Enabled = false;
            GroupTrace.Send("GroupTrace traces 2"); // not send : group not enabled

            // ensure all traces are send to the viewer
            TTrace.Flush();
        }