Pages

Showing posts with label output. Show all posts
Showing posts with label output. Show all posts

Wednesday, November 19, 2014

Be careful with Path.Combine

Yesterday I was pointed out that there is a security problem with my code. I was coding the async file uploader (will post it little later) and it is able to delete unused files as well. It is done with a post of a filename and that filename is stored in a hidden input. Everything is fine with that but the problem is in my usage of the Path.Combine method.

Here is a snippet:
 var p1 = "C:\\Test";
 var p2 = "C:\\NOT_A_TEST\\File.txt";
 var p3 = "File.txt";
 
 Console.WriteLine(Path.Combine(p1, p2)); //result is "C:\NOT_A_TEST\File.txt"
 Console.WriteLine(Path.Combine(p1, p3)); //all good - C:\Test\File.txt
 
 //and 2 safe methods:
 Console.WriteLine(Path.Combine(p1, Path.GetFileName(p2))); 
 Console.WriteLine(Path.Combine(p1, Path.GetFileName(p3)));

So if you want to use path combine - make sure that the last part of it is only a filename, not the whole path as it can overwrite the whole result! And as aa side-note
 Console.WriteLine(Path.GetFileNameWithoutExtension("C:\\Test\\test.txt")); 

Will return 'test', so it is as safe as Path.GetFileName.

Friday, April 5, 2013

Redirection of the Input/Output for processes

It is very comfortable to have redirected input and output for your console processes. For example, lets imagine a situation when you have to start scripts from your application (it might be something like script manager). So you have a collection of running processes and in order to handle them properly you have to start them with different arguments, get their messages, handle (or log) their exceprions.
Fortunately there is an easy way to achieve it. We can use RedirectStandartOutput, RedirectStandartInput and RedirectStandartError properties of the ProcessStartInfo class.
First of all we have to set those properties to true, then we have to set UseShellExecute propertie to false (because it allows us to redirect streams) and, finally, process different events. And do not forget to start listening to those streams!
Here is a simple example to run vbs script in a hidden way:

System.Diagnostics.Process p = new System.Diagnostics.Process();

p.StartInfo = new System.Diagnostics.ProcessStartInfo("cscript");
p.StartInfo.Arguments = "C:\\test.vbs";

p.StartInfo.CreateNoWindow = true;
p.StartInfo.UseShellExecute = false;

p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;

p.OutputDataReceived += (proc, outLine) => LogMessage(outLine.Data);
p.ErrorDataReceived += (proc, outLine) => LogError(outLine.Data);

p.Start();
p.BeginOutputReadLine();
p.BeginErrorReadLine ();