How to avoid Reflected_xss_all_clients vulnerabilities in Winforms c# - c#

Currently, I am working for a Winforms project.
When I am scanning my Winforms application through CheckMarx then I am getting multiple Reflected_xss_all_clients vulnerabilities.
I know there is no scripting in Winforms. XSS is a web threat but may be there would be some way to remediate these threats during scanning.
Here is the error code section 1:
private void UpdatePreviewValue()
{
try
{
// Set the preview value
if (txtFieldValue.Text != string.Empty)
{
// Show the preview value
lblPreview.Text = "(" + txtFieldValue.Text + ")";
}
else
{
// Show that there is no field value
lblPreview.Text = Properties.Resources.Std_Txt_Fld_NoFieldValue;
}
}
catch (Exception ex)
{
frmErrorHandler.ShowDataError(Properties.ErrorStrings.ErrorTitle_SrcFldCtlInteger_UpdatePreviewValue, DataErrorImageConstants.Exclamation, ex);
}
}
in above code section, the line lblPreview.Text = "(" + txtFieldValue.Text + ")";is throwing Reflected_xss_all_clients vulnerabilities.
Here is the error code section 2:
/// <summary>
/// Method to copy an existing node for moving inside a grid
/// </summary>
/// <param name="rowToCopy">GridRow to copy</param>
/// <returns>GridRow</returns>
private GridRow CopyGridRow(GridRow rowToCopy)
{
GridRow newRow = gridCategories.NewRow();
newRow.Tag = rowToCopy.Tag;
newRow.Cells[0].Text = rowToCopy.Cells[0].Text;
newRow.Cells[0].Image = rowToCopy.Cells[0].Image;
newRow.Cells[1].Text = rowToCopy.Cells[1].Text;
if (rowToCopy.HasRows)
{
foreach (GridRow nestedRow in rowToCopy.NestedRows)
{
newRow.NestedRows.Add(CopyGridRow(nestedRow));
}
}
return newRow;
}
in above code section, the line newRow.Cells[0].Text = rowToCopy.Cells[0].Text; and newRow.Cells[1].Text = rowToCopy.Cells[1].Text;are throwing Reflected_xss_all_clientsvulnerabilities.
Here is the error code section 3:
/// <summary>
/// Method used to add a new discrete value to the listview
/// </summary>
private void AddDiscreteValue()
{
// check we have an entry to add
if (txtDiscreteValue.Text != "")
{
SetDiscreteValue(txtDiscreteValue.Text, true, null, false);
}
}
In above code section, the line SetDiscreteValue(txtDiscreteValue.Text, true, null, false); is throwing Reflected_xss_all_clients vulnerabilities for txtDiscreteValue.Text
Please suggest any way to remediate it, if possible.

Checkmarx will follow the string from input to use. Sometimes it identifies a variable which is not fillterd transited to the frontend as a XSS.
As for me, I always ignore the XSS reported from Checkmarx. Maybe you can use a fillter function before use the string variable. Like this
txtFieldValue.Text=cleanXSS(txtFieldValue.Text)
As for cleanXSS(), you can find many examples after google.

Related

A C# Method to Import Block Definitions into AutoCAD

I'm trying to write a method to programmatically import blocks into a drawing so that my .NET plugin can place instances of those blocks into the drawing. Right now my method looks like this:
/// <summary>
/// Method to programatically import all the blocks in a given list
/// </summary>
public static void ImportBlocks(string[] filesToTryToImport)
{
//Importing all the blocks
for (int i = 0; i < filesToTryToImport.Count(); i++)
{
if (filesToTryToImport[i].EndsWith(".dwg"))
{
try
{
Transaction tr = _database.TransactionManager.StartTransaction();
DocumentLock docLock = _activeDocument.LockDocument();
using (tr)
using (docLock)
{
BlockTable blkTbl = tr.GetObject(_database.BlockTableId, OpenMode.ForRead) as BlockTable;
// ToDo: Add files
}
}
catch (Autodesk.AutoCAD.Runtime.Exception ex)
{
_editor.WriteMessage("\nError during copy: " + ex.Message);
}
}
}
}
And what I want is for all the blocks whose filepaths are in the string array filesToTryToImport to appear as options when I go to insert a block
So, for example, if One-Inch-Block wasn't originally in the list but the file path to it was passed as a string in the array passed to this method it becomes an option.

Best way to collect and store times and dates

This question might be a little ambiguous so I'll explain my goal and my previous implementation. I'm looking for some advice on how to improve my implementation.
My application needs a certain set of days and times (hours and minutes) to be used for criteria later in the program.
The days and times are variable and depend on whether a user is a member of a particular group or not.
My previous implementation was to get the name of the group that was selected and then go to the web server and download the appropriate file which contained the day and time. There was a file for each group.
The format of the text file was:
Day,Day,Day,etc..HH,HH,MM,MM
It was then read into two separate arrays with the positions hardcoded. E.g. Index 0, 1,2 where days while 3,4 where hours and 5,6 where minutes.
This method also meant that I'd need a longer array for a group that had more days than another.
Obviously this was all very inefficient and the code wasn't very reusable or extendable. I'd have to alter if a new group was introduced and it had more of less data in the text file.
Edit - due to the vagueness of the question I have included code:
This method is passed the group name in the fileName parameter of CollectQualifyingTimes. The string looked like gtstimes.txt or gtsdates.txt or gectimes.txt or gecdates.txt
internal static class DownloadQualifyingTimes
{
//TimeDate Arrays
public static readonly List<string> QDaysList = new List<string>();
public static readonly List<int> QTimesList = new List<int>();
private static StreamReader _reader;
private static string _line;
private static string _file;
/// <summary>
/// Collects the Times
/// </summary>
public static void CollectQualifyingTimes(string fileName)
{
Logger.Debug("About to download the " + fileName + " Qualifying Times and Dates");
FileDownload.DownloadOnlineFile(fileName);
OpenQualifyingFile(fileName);
}
/// <summary>
/// Open the qualifying file and read the values.
/// </summary>
/// <returns></returns>
private static void OpenQualifyingFile(string fileName)
{
try
{
_file = Path + "\\" + fileName;
using (_reader = new StreamReader(_file))
{
while ((_line = _reader.ReadLine()) != null)
{
if (fileName.Contains("Times"))
{
QTimesList.Add(Convert.ToInt16(_line));
Logger.Debug("Times " + _line);
}
else
{
QDaysList.Add(_line);
Logger.Debug("Days " + _line);
}
}
}
}
catch (WebException exception)
{
Logger.Error(exception);
}
}
}
//The method that calls the Downloading class looks like this:
/// <summary>
///
/// </summary>
/// <param name="selectedLeague"></param>
/// <returns></returns>
public static bool QualificationTimeCheck(string selectedLeague)
{
var currentUtcTime = DateTime.UtcNow;
//Day check regardless of league
if (DownloadQualifyingTimes.QDaysList.Contains(currentUtcTime.DayOfWeek.ToString()))
{
Logger.Debug("Qualifying day condition meet");
if (selectedLeague.IsOneOf("GTS", "CAT"))
{
Logger.Debug("GTS or CAT qualifying logic");
if (currentUtcTime.Hour ==
DownloadQualifyingTimes.QTimesList[0] ||
currentUtcTime.Hour ==
DownloadQualifyingTimes.QTimesList[1])
{
Logger.Debug("Qualifying hour condition meet");
if (((currentUtcTime.Minute > DownloadQualifyingTimes.QTimesList[2])
&& (currentUtcTime.Minute < DownloadQualifyingTimes.QTimesList[3])) || SessionObject.LastLapStartedMinute <= DownloadQualifyingTimes.QTimesList[3])
{
Logger.Debug("Qualifying minute condition meet");
return true;
}
I hope this illustrates the nature of my question and the problem.
Can you think of a better way to implement this process? If you need any more information regarding it please don't hesitate to ask.
Edit - Ended up implementing List as per first comment suggestion.

How to refer to an identifier without writing it into a string literal in C#?

I often want to do this:
public void Foo(Bar arg)
{
throw new ArgumentException("Argument is incompatible with " + name(Foo));
}
Because if I change the name of Foo the IDE will refactor my error message too, what won't happen if I put the name of the method (or any other kind of member identifier) inside a string literal. The only way I know of implementing "name" is by using reflection, but I think the performance loss outweighs the mantainability gain and it won't cover all kinds of identifiers.
The value of the expression between parenthesis could be computed at compile time (like typeof) and optimized to become one string literal by changing the language specification. Do you think this is a worthy feature?
PS: The first example made it look like the question is related only to exceptions, but it is not. Think of every situation you may want to reference a type member identifier. You'll have to do it through a string literal, right?
Another example:
[RuntimeAcessibleDocumentation(Description="The class " + name(Baz) +
" does its job. See method " + name(DoItsJob) + " for more info.")]
public class Baz
{
[RuntimeAcessibleDocumentation(Description="This method will just pretend " +
"doing its job if the argument " + name(DoItsJob.Arguments.justPretend) +
" is true.")]
public void DoItsJob(bool justPretend)
{
if (justPretend)
Logger.log(name(justPretend) + "was true. Nothing done.");
}
}
UPDATE: this question was posted before C# 6, but may still be relevant for those who are using previous versions of the language. If you are using C# 6 check out the nameof operator, which does pretty much the same thing as the name operator in the examples above.
well, you could cheat and use something like:
public static string CallerName([CallerMemberName]string callerName = null)
{
return callerName;
}
and:
public void Foo(Bar arg)
{
throw new ArgumentException("Argument is incompatible with " + CallerName());
}
Here, all the work is done by the compiler (at compile-time), so if you rename the method it will immediately return the correct thing.
If you simply want the current method name: MethodBase.GetCurrentMethod().Name
If it's a type typeof(Foo).Name
If you want the name of a variable/parameter/field/property, with a little Expression tree
public static string GetFieldName<T>(Expression<Func<T>> exp)
{
var body = exp.Body as MemberExpression;
if (body == null)
{
throw new ArgumentException();
}
return body.Member.Name;
}
string str = "Hello World";
string variableName = GetFieldName(() => str);
For method names it's a little more tricky:
public static readonly MethodInfo CreateDelegate = typeof(Delegate).GetMethod("CreateDelegate", BindingFlags.Static | BindingFlags.Public, null, new[] { typeof(Type), typeof(object), typeof(MethodInfo) }, null);
public static string GetMethodName<T>(Expression<Func<T>> exp)
{
var body = exp.Body as UnaryExpression;
if (body == null || body.NodeType != ExpressionType.Convert)
{
throw new ArgumentException();
}
var call = body.Operand as MethodCallExpression;
if (call == null)
{
throw new ArgumentException();
}
if (call.Method != CreateDelegate)
{
throw new ArgumentException();
}
var method = call.Arguments[2] as ConstantExpression;
if (method == null)
{
throw new ArgumentException();
}
MethodInfo method2 = (MethodInfo)method.Value;
return method2.Name;
}
and when you call them you have to specify the type of a compatible delegate (Action, Action<...>, Func<...> ...)
string str5 = GetMethodName<Action>(() => Main);
string str6 = GetMethodName<Func<int>>(() => Method1);
string str7 = GetMethodName<Func<int, int>>(() => Method2);
or more simply, without using expressions :-)
public static string GetMethodName(Delegate del)
{
return del.Method.Name;
}
string str8 = GetMethodName((Action)Main);
string str9 = GetMethodName((Func<int>)Method1);
string str10 = GetMethodName((Func<int, int>)Method2);
As has been covered, using this approach for exceptions seems unnecessary due to the method name being in the call stack on the exception.
In relation to the other example in the question of logging the parameter value, it seems PostSharp would be a good candidate here, and probably would allow lots of new features of this kind that you're interested in.
Have a look at this page on PostSharp which came up when I searched for how to use PostSharp to log parameter values (which it covers). An excerpt taken from that page:
You can get a lot of useful information with an aspect, but there are three popular categories:
Code information: function name, class name, parameter values, etc. This can help you to reduce guessing in pinning down logic flaws or edge-case scenarios
Performance information: keep track of how much time a method is taking
Exceptions: catch select/all exceptions and log information about them
The original question is named "How to refer to an identifier without writing it into a string literal in C#?" This answer does not answer that question, instead, it answers the question "How to refer to an identifier by writing its name into a string literal using a preprocessor?"
Here is a very simple "proof of concept" C# preprocessor program:
using System;
using System.IO;
namespace StackOverflowPreprocessor
{
/// <summary>
/// This is a C# preprocessor program to demonstrate how you can use a preprocessor to modify the
/// C# source code in a program so it gets self-referential strings placed in it.
/// </summary>
public class PreprocessorProgram
{
/// <summary>
/// The Main() method is where it all starts, of course.
/// </summary>
/// <param name="args">must be one argument, the full name of the .csproj file</param>
/// <returns>0 = OK, 1 = error (error message has been written to console)</returns>
static int Main(string[] args)
{
try
{
// Check the argument
if (args.Length != 1)
{
DisplayError("There must be exactly one argument.");
return 1;
}
// Check the .csproj file exists
if (!File.Exists(args[0]))
{
DisplayError("File '" + args[0] + "' does not exist.");
return 1;
}
// Loop to process each C# source file in same folder as .csproj file. Alternative
// technique (used in my real preprocessor program) is to read the .csproj file as an
// XML document and process the <Compile> elements.
DirectoryInfo directoryInfo = new DirectoryInfo(Path.GetDirectoryName(args[0]));
foreach (FileInfo fileInfo in directoryInfo.GetFiles("*.cs"))
{
if (!ProcessOneFile(fileInfo.FullName))
return 1;
}
}
catch (Exception e)
{
DisplayError("Exception while processing .csproj file '" + args[0] + "'.", e);
return 1;
}
Console.WriteLine("Preprocessor normal completion.");
return 0; // All OK
}
/// <summary>
/// Method to do very simple preprocessing of a single C# source file. This is just "proof of
/// concept" - in my real preprocessor program I use regex and test for many different things
/// that I recognize and process in one way or another.
/// </summary>
private static bool ProcessOneFile(string fileName)
{
bool fileModified = false;
string lastMethodName = "*unknown*";
int i = -1, j = -1;
try
{
string[] sourceLines = File.ReadAllLines(fileName);
for (int lineNumber = 0; lineNumber < sourceLines.Length - 1; lineNumber++)
{
string sourceLine = sourceLines[lineNumber];
if (sourceLine.Trim() == "//?GrabMethodName")
{
string nextLine = sourceLines[++lineNumber];
j = nextLine.IndexOf('(');
if (j != -1)
i = nextLine.LastIndexOf(' ', j);
if (j != -1 && i != -1 && i < j)
lastMethodName = nextLine.Substring(i + 1, j - i - 1);
else
{
DisplayError("Unable to find method name in line " + (lineNumber + 1) +
" of file '" + fileName + "'.");
return false;
}
}
else if (sourceLine.Trim() == "//?DumpNameInStringAssignment")
{
string nextLine = sourceLines[++lineNumber];
i = nextLine.IndexOf('\"');
if (i != -1 && i != nextLine.Length - 1)
{
j = nextLine.LastIndexOf('\"');
if (i != j)
{
sourceLines[lineNumber] =
nextLine.Remove(i + 1) + lastMethodName + nextLine.Substring(j);
fileModified = true;
}
}
}
}
if (fileModified)
File.WriteAllLines(fileName, sourceLines);
}
catch (Exception e)
{
DisplayError("Exception while processing C# file '" + fileName + "'.", e);
return false;
}
return true;
}
/// <summary>
/// Method to display an error message on the console.
/// </summary>
private static void DisplayError(string errorText)
{
Console.WriteLine("Preprocessor: " + errorText);
}
/// <summary>
/// Method to display an error message on the console.
/// </summary>
internal static void DisplayError(string errorText, Exception exceptionObject)
{
Console.WriteLine("Preprocessor: " + errorText + " - " + exceptionObject.Message);
}
}
}
And here's a test file, based on the first half of the original question:
using System;
namespace StackOverflowDemo
{
public class DemoProgram
{
public class Bar
{}
static void Main(string[] args)
{}
//?GrabMethodName
public void Foo(Bar arg)
{
//?DumpNameInStringAssignment
string methodName = "??"; // Will be changed as necessary by preprocessor
throw new ArgumentException("Argument is incompatible with " + methodName);
}
}
}
To make the running of the preprocessor program a part of the build process you modify the .csproj file in two places. Insert this line in the first section:
<UseHostCompilerIfAvailable>false</UseHostCompilerIfAvailable>
(This is optional - see here https://stackoverflow.com/a/12163384/253938 for more information.)
And at the end of the .csproj file replace some lines that are commented-out with these lines:
<Target Name="BeforeBuild">
<Exec WorkingDirectory="D:\Merlinia\Trunk-Debug\Common\Build Tools\Merlinia Preprocessor\VS2012 projects\StackOverflowPreprocessor\bin" Command="StackOverflowPreprocessor.exe "$(MSBuildProjectFullPath)"" />
</Target>
Now when you recompile the test program the line that says
string methodName = "??"; // Will be changed as necessary by preprocessor
will be magically converted to say
string methodName = "Foo"; // Will be changed as necessary by preprocessor
OK?
Version 6 of C# has introduced the nameof operator which works like the name operator described in the examples of the question, but with some restrictions. Here are some examples and excerpts from the C# FAQ blog:
(if x == null) throw new ArgumentNullException(nameof(x));
You can put more elaborate dotted names in a nameof expression, but that’s just to tell the compiler where to look: only the final identifier will be used:
WriteLine(nameof(person.Address.ZipCode)); // prints "ZipCode"
Note: there are small design changes to nameof since the Preview was built. In the preview, dotted expressions like in the last example, where person is a variable in scope, are not allowed. Instead you have to dot in through the type.

strange behavior of XamlReader.Load()?

I've got a very strange issue while parsing an external XAML file. The pre-history is that I want to load an external XAML file with content to process. But I want to load as many different files as I want. That happens by unloading the old and loading the new one.
My issue is:
When I load a xaml the first time, everything is good, all as it should be.
But when I load the same xaml the second time, every entry of the object im Loading is there twice. If I run this again, every object is there three times and so on...
To debug the project yourself, download it here. The function starts at line 137 in the file "Control Panel.xaml.cs". I realy don't know what this is. Is it my fault or simply a bug? If yes, is there a workaround?
/// <summary>
/// Load a xaml file and parse it
/// </summary>
public void LoadPresentation()
{
this.Title = "Control Panel - " + System.IO.Path.GetFileName(global.file);
System.IO.FileStream XAML_file = new System.IO.FileStream(global.file, System.IO.FileMode.Open);
try
{
System.IO.StreamReader reader = new System.IO.StreamReader(XAML_file);
string dump = reader.ReadToEnd(); //This is only for debugging purposes because of the strange issue...
XAML_file.Seek(0, System.IO.SeekOrigin.Begin);
presentation = (ResourceDictionary)XamlReader.Load(XAML_file);
//Keys the resourceDictionary must have to be valid
if (presentation["INDEX"] == null || presentation["MAIN_GRID"] == null || presentation["CONTAINER"] == null || presentation["LAYOUTLIST"] == null)
{
throw new Exception();
}
//When this list is loaded, every item in it is there twice or three times or four... Why????
TopicList Index = null;
Index = (TopicList)presentation["INDEX"];
for (int i = 0; i < topics.Count; )
{
topics.RemoveAt(i);
}
foreach (TopicListItem item in Index.Topics)
{
topics.Insert(item.TopicIndex, (Topic)presentation[item.ResourceKey]);
}
lv_topics.SelectedIndex = 0;
selectedIndex = 0;
}
catch
{
System.Windows.Forms.MessageBox.Show("Failed to load XAML file \"" + global.file + "\"", "Parsing Error", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
presentation = null;
}
finally
{
XAML_file.Close();
}
}
Edit:
I have tried to serialize the object that was read from the XamlReader and in the output was nowhere any childelement... But if I pull the object out of the dictionary, the children are all there (duplicated and triplicated, but there).
I have already tried to clear the list over
topics.Clear();
and
topics=new ObservableCollection<TopicListItem>();
lv_topics.ItemsSource=topics;
Try Index.Topics.Clear() after loading the Topics into your topics object. That appears to get rid of the duplication.
//When this list is loaded, every item in it is there twice or three times or four... Why????
TopicList Index = null;
Index = (TopicList)presentation["INDEX"];
topics.Clear();
foreach (TopicListItem item in Index.Topics)
{
topics.Insert(item.TopicIndex, (Topic)presentation[item.ResourceKey]);
}
Index.Topics.Clear(); //Adding this will prevent the duplication
lv_topics.SelectedIndex = 0;
selectedIndex = 0;
In the code post topics is not declared in LoadPresentation() so naturally it will have any prior values.
I know you said you tried topics=new ObservableCollection(); but please try again. And put that IN LoadPresentation()
public void LoadPresentation()
{
ObservableCollection<TopicListItem> topics = new ObservableCollection<TopicListItem>()
I would pass filename
public void LoadPresentation(string fileName)
I get you may need to use topics outside LoadPresentation but this is debugging. If you need topics outside the return it.
public ObservableCollection<TopicListItem> LoadPresentation(string fileName)
If that does not fix it I would put a try catch block on the XAML_file.Close(); to see if something weird is not going on.

Set class property at runtime

I have a problem with my code, I cannot get it the 'test' to get the values im trying to assign to it.
rec = new Record(perosn, actually, com, Centre, CCentre);
webservicename.singleSummary test = new webservicename.singleSummary();
test.person = rec.person;
test.actually = recc.Actually;
test.com = rec.Com;
test.Centre = rec.Centre;
test.CCentre = rec.CCentre;
webservicename.Feed CallWebService = new webservicename.Feed();
I am trying to get this to pop up in a dialog box to show that it is working, with something like test.account getting showed in the message box, not sure quite what the problem is.
My overall problem is I am trying to set the class porpert at runtime.
Any help is appreciated.
Is "Record" an existing class?
Is this a compile time error and what does the error say?
One simple solution might be to debug into this using visual studio and check the values there, (if your using Visual Studio).
If you're trying check these values at run time (not development time) then you could use javascript to display a message.
Thanks to a WebProNew.com article...http://www.webpronews.com/expertarticles/2006/11/29/javascript-alertshowmessage-from-aspnet-codebehind
using System.Web;
using System.Text;
using System.Web.UI;
///
/// A JavaScript alert
///
public static class Alert
{
///
/// Shows a client-side JavaScript alert in the browser.
///
/// The message to appear in the alert.
public static void Show(string message)
{
// Cleans the message to allow single quotation marks
string cleanMessage = message.Replace("'", "\\'");
string script = "alert('" + cleanMessage + "');";
// Gets the executing web page
Page page = HttpContext.Current.CurrentHandler as Page;
// Checks if the handler is a Page and that the script isn't allready on the Page
if (page != null && !page.ClientScript.IsClientScriptBlockRegistered("alert"))
{
page.ClientScript.RegisterClientScriptBlock(typeof(Alert), "alert", script);
}
}
}
Usage...
void btnSave_Click(object sender, EventArgs e)
{
try
{
SaveSomething();
Alert.Show("You document has been saved");
}
catch (ReadOnlyException)
{
Alert.Show("You do not have write permission to this file");
}
}

Categories

Resources