My application is using Process.Start for opening another application to run. VeraCode [a security software scanning tool] reported this command as OS Command Injection Vulnerable. I would like to get some comment. I have found a lot of information on the web regarding to filter the input or to constraint the program name; however, I am curious to see if there's any other alternatives of using Process.Start?
Edit:
Thanks for the comment, here is one of the sample, and yes, it is getting input from users:
public static void Run(string fileName, string arguments, bool waitForExit)
{
Process p = Process.Start(fileName, arguments);
if (waitForExit)
p.WaitForExit();
}
Thanks!
This is a command injection vulnerability because you have not filtered out the users input from the function and directly appended to the process.start()
Due to this, the tool has marked it as a vulnerability.
To avoid this issue you should use regex method to filter out the bad characters and depending on what that function is going to do when it gets run.
for eg. you function is created only to check from this path c:/users/docs.txt
then that function should not get executed for c:/admin/docs.txt.
This is how you need to validate before sending the user data directly into the process.
For more information refer this awesome link : https://dotnet-security-guard.github.io/SG0001.htm
or
https://www.veracode.com/security/dotnet/cwe-78
The Process class is nothing else then a Managed wrapper class the the Native Create Process and its Variations like Create Process As User .
Process MSDN
Process
SourceCode
I don't think that there is another way to start a process than this, because every other solution would also call the WinAPI function. ( because this function (or its overloads and Variations) is the only way to start a process in Windows).
Personally, I have not heard anything about a problem with Process.Start please clarify the problem
regards
I ran into this as well. You need to set the UseShellExecute property to false. Then Veracode will not consider it a vulnerability.
using (WinProcess myProcess = new WinProcess())
{
myProcess.StartInfo.FileName = "notepad.exe";
myProcess.StartInfo.Arguments = Path.GetFileName(fullPath);
myProcess.StartInfo.UseShellExecute = false;
myProcess.StartInfo.WorkingDirectory = Path.GetDirectoryName(fullPath);
myProcess.StartInfo.RedirectStandardOutput = false;
myProcess.Start();
}
Related
When I execute the following line of code:
Process.Start("microsoft-edge:");
Or
Process.Start("microsoft-edge:http://localhost");
It gives me this error:
System.ComponentModel.Win32Exception: 'The system cannot find the file specified.'
When I run microsoft-edge: using Win+R it works.
When I run the same code in .net framework it works.
I'm using .netcore 3.0.0-preview6-27804-01
Any idea why this is happening?
Edit:
These are not working either:
Process.Start(#"c:\Windows\System32\LaunchWinApp.exe:http://localhost");
Process.Start(#"http://localhost");
All other executables on my system work.
Also this is working too but I can't open a specific webpage with it:
Process.Start("explorer", #"shell:Appsfolder\Microsoft.MicrosoftEdge_8wekyb3d8bbwe!MicrosoftEdge");
You cannot simply open a url with the expected call Process.Start("url");
You have to create a ProcessStartInfo and pass your browser and url as arguments:
Process.Start(new ProcessStartInfo("cmd", $"/c start microsoft-edge:http://localhost") { CreateNoWindow = true });
(edit) The use of ProcessStartInfo is required because we need to set its CreateNoWindow = true to prevent cmd window from showing up.
But as this code not only can be run on a Windows machine, i'd consider using something more cross-platform specific like this (https://brockallen.com/2016/09/24/process-start-for-urls-on-net-core/):
public void OpenBrowser(string url)
{
try
{
Process.Start(url);
}
catch
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
Process.Start(new ProcessStartInfo("cmd", $"/c start {url}") { CreateNoWindow = true });
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
Process.Start("xdg-open", url);
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
Process.Start("open", url);
}
else
{
throw;
}
}
}
And call it with OpenBrowser("http://localhost");
The exact root cause is indicated here: https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.processstartinfo.useshellexecute?view=netframework-4.8
"The default is true on .NET Framework apps and false on .NET Core apps."
This means the direct solution is to set UseShellExecute. The following is basically the same as the original except making an explicit Process object to modify a setting.
Process pWeb = new Process();
pWeb.StartInfo.UseShellExecute = true;
pWeb.StartInfo.FileName = "microsoft-edge:http://localhost";
pWeb.Start();
Credit to #Lex Li and #Bizhan for their comments leading to this solution.
This variation seems to do the job as well:
Process.Start(new ProcessStartInfo("msedge") {
UseShellExecute = true,
Arguments = "http://localhost" });
It avoids the strangeness of the microsoft-edge:<url> syntax thus allowing for more chrome arguments to be passed in the usual way.
If anyone knows of a reason to avoid this, feel free to speak up :)
Windows Run window (Win+R) know how to resolve "microsoft-edge:" to the Path Of Executable. When you call it through Run window, it first resolves to the path. Then the actual executable from that path is executed.
With Process.Start, there is no this resolution of path. It only look for some paths like application path or PATH variables. Obviously, it does not find the executable to run and hence the error.
If you have a path variable declared in your system using quotes, you must fully qualify that path when starting any process found in that location. Otherwise, the system will not find the path. For example, if c:\mypath is not in your path, and you add it using quotation marks: path = %path%;"c:\mypath", you must fully qualify any process in c:\mypath when starting it.
Source
Note that command line parameters are not allowed by this overload:
This overload does not allow command-line arguments for the process. If you need to specify one or more command-line arguments for the process, use the Process.Start(ProcessStartInfo) or Process.Start(String, String) overloads.
I am trying to write a C# program that is supposed to call the runas tool from windows and input the password automatically.
What I tried:
Process runas = new Process();
runas.StartInfo.FileName = "runas";
runas.StartInfo.UseShellExecute = false;
runas.StartInfo.RedirectStandardInput = true;
runas.StartInfo.Arguments = "\"/user:domain\\username\" \"cmd.exe\"";
runas.Start();
StreamWriter stream = runas.StandardInput;
stream.WriteLine("our super secret password");
stream.Flush();
stream.Close();
runas.WaitForExit();
runas.Close();
What happended:
I get the following output.
Please enter the password for "...":
Trying to execute cmd.exe as user "kfz\dummy"...
RUNAS-ERROR: cmd.exe could not be executed
1326: Authentication failed: unknown username or password.
(translated by me from my german windows)
Yes, I quadrupel checked the password and username. Entering everything by hand in the command line works fine.
What I experimented with:
I tried redirecting the Output as well and reading from it, no success.
I tried different variants of writing to the stream:
stream.Write("our super secret password");
stream.Write("our super secret password\n");
stream.Write("our super secret password\r\n");
All results in the same behaviour.
What I noticed:
The runas process seems not to wait for me to write to the stream.
I added a Sleep before writing and I immediately got the above output.
I am afraid runas uses some nonstd-input.....
Research result:
Upon trying to find out what kind of input runas uses I was not successfull.
I found an alternative to the windows builtin runas here however I would prefer not to use it although I might fall back to it if it is impossible to do.
EDIT:
Ok I found sources that say microsoft deliberately prevented people from doing that.....
I hate it when someone does that! If I WANT to use something that is not secure then who is microsoft to keep me from that!
Sorry I got off topic.
One question remains... Can we still get around it somehow? Can we hack runas? ;)
The whole reason why you're not supposed to do that is because there's an API for that.
No need to use runas.
ProcessStartInfo lets you specify the UserName and Password directly.
For example:
var psi = new ProcessStartInfo();
psi.Domain = "YourDomain";
psi.UserName = "YourUserName";
psi.Password = securePassword;
psi.FileName = "cmd.exe";
Process.Start(psi);
I'm trying to run a program, say "robocopy.exe", through an aspx page using the System.Diagnostics.Process object.
My code looks like this:
Process si = new Process();
si.StartInfo.UserName = "testuser";
si.StartInfo.Password = password;
si.StartInfo.FileName = "cmd.exe";
si.StartInfo.UseShellExecute = false;
si.StartInfo.Arguments = "c/ robocopy.exe";
si.Start();
string output = si.StandardOutput.ReadToEnd();
si.Close();
Label1.Text = output;
The problem is that the cmd.exe process is started correctly, but nothing happens. The argument of roboxopy.exe is presumably not passed to the cmd process to run! Any ideas as to what Icould be doing wrong?
Sounds like a permission issue. Usually the default asp_net account that any IIS processes run under will not have execute permissions on the server. The reason that this is the case is because it is a huge security hole. I would highly recommend that you think about what you are trying to accomplish and see if there is another way to do it that does not involve running a separate executable.
I using C# .NET , vs 2008 , .net 3.5
For me, is difficult, but I need sample code in C# for this:
Check if a file or a folder is in use
If file or a folder is in use, the name of Process that use it
For example, in my issue.
I try delete file, and I get "The process cannot access the file 'XYZ' because it is being used by another process." Exception.
File.Delete(infoFichero.Ruta);
I want check if a file is in use, and the name of Process that use it.
I need sample code, source code, please. I dont want use c++, I dont know c, c++, unmanaged code, or WinApi. I want use only C# code (managed code .net).
I have read several references but not get sample code source,
How to check if a file is in use?
Emulate waiting on File.Open in C# when file is locked
http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/9dabc172-237a-42db-850e-ada08885a5d5
How to check if a file is in use?
Easiest way to read text file which is locked by another application
Using C# is it possible to test if a lock is held on a file
EDIT:
From Yan Jun - MSFT
string path = "D:\\temp2.xlsx";
foreach (Process c in Process.GetProcesses()) {
if (c.MainWindowTitle.Contains(Path.GetFileName(path))){
MessageBox.Show(c.ProcessName);
return;
}
}
try{
FileInfo f = new FileInfo(path);
f.Delete();
}
catch (Exception ex){
MessageBox.Show(ex.Message);
}
...
But it is difficult get solution for all 100% issues.
Problem if c.MainWindowTitle == null or not contains filename.
Problem for shared folder in another machine, PC, server,... like:
File.Delete(#\desiis\TEmporal\Project\script.targets);
any sample code, I ask for help gurus, MVPs, anyone.
UPDATE: the same issue for a folder
There's not going to be a way to find the process that has the file opened without stepping into the WinApi, I don't think. And as far as checking whether its in use, the only thing you can really do, as the SO questions you linked to state, is to wrap the file access attempts in a try/catch block.
The code to find which file has it opened is likely to be ugly, but there may be an API out there that wraps this up nicely. There are 3rd party utilities that will tell you this (Unlocker being the best known example). You can also use ProcessExplorer to search for open file handles by the filename. Those don't really help you though.
The short answer of what I'm trying to get across here is you have the answer for the first part of your question in the SO questions you already linked, and the second part would probably require WIN32 calls, which you want to avoid, but you're probably going to have to get your hands dirty in Win32... Still want help?
EDIT: You could shell out to sysinternals Handle utility. You would need to get the output of that command and parse it yourself. You can read the executed process's output like this
string result = proc.StandardOutput.ReadToEnd();
The issue with this is you're going to get a license agreement popup the first time you run the Handle utility. Not to mention the whole licensing issues if this is something you hope to deploy...
If you're still interested, I can show you how you'd go about this.
EDIT: Here's a runnable program that will find the exe name and pid of any program that has an open handle to a file. I added comments, but can elaborate further if necessary. I use Regular Expressions here to parse the output as that makes the most sense given the task at hand.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Text.RegularExpressions;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
ProcessStartInfo si = new ProcessStartInfo();
si.FileName = "handle.exe"; //name of the handle program from sysinternals
//assumes that its in the exe directory or in your path
//environment variable
//the following three lines are required to be able to read the output (StandardOutput)
//and hide the exe window.
si.RedirectStandardOutput = true;
si.WindowStyle = ProcessWindowStyle.Hidden;
si.UseShellExecute = false;
si.Arguments = "test.xlsx"; //this is the file you're trying to access that is locked
//these 4 lines create a process object, start it, then read the output to
//a new string variable "s"
Process p = new Process();
p.StartInfo = si;
p.Start();
string s = p.StandardOutput.ReadToEnd();
//this will use regular expressions to search the output for process name
//and print it out to the console window
string regex = #"^\w*\.EXE";
MatchCollection matches = Regex.Matches(s, regex, RegexOptions.Multiline);
foreach (var match in matches)
{
Console.WriteLine(match);
}
//this will use regex to search the output for the process id (pid)
//and print it to the console window.
regex = #"pid: (?<pid>[0-9]*)";
matches = Regex.Matches(s, regex, RegexOptions.Multiline);
foreach (var obj in matches)
{
Match match = (Match)obj; //i have to cast to a Match object
//to be able to get the named group out
Console.WriteLine(match.Groups["pid"].Value.ToString());
}
Console.Read();
}
}
}
There is no purely managed way to do this. You have to use some low-level APIs through P/invoke or similar.
There's good information here on a way to do it, but it's C++ code. You'd have to do the porting yourself.
http://www.codeproject.com/KB/shell/OpenedFileFinder.aspx
Note there are some complex issues with this, namely the issues around kernel vs. userspace memory. This is not a simple problem you're trying to solve.
Try the windows Process Explorer:
http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx
Won't let you do it from code, but at least you can figure out what the source of your locks are.
I'm currently trying to get the output of an executable console-app into an other one. To be exact, a little overview of what I'm trying to do:
I have one executable which I cannot edit and neither see it's code. It writes some (quite a bunch to be honest) lines into the console when executed.
Now I want to write another executable that starts the one above and reads the things it writes.
Seems simple to me, so I started coding but ended up with an error message saying that StandardOut has not been redirected or the process hasn't started yet.
I tried it using this kinda structure (C#):
Process MyApp = Process.Start(#"C:\some\dirs\foo.exe", "someargs");
MyApp.Start();
StreamReader _Out = MyApp.StandardOutput;
string _Line = "";
while ((_Line = _Out.ReadLine()) != null)
Console.WriteLine("Read: " + _Line);
MyApp.Close();
I can open the executable and it also does open the one inside, but as soon as it comes to reading the returned values, the app crashes.
What am I doing wrong?!
Take a look at the documentation for the Process.StandardOutput property. You will need to set a boolean indicating that you want the stream redirected as well as disabling shell execute.
Note from the documentation:
To use StandardOutput, you must set ProcessStartInfo..::.UseShellExecute to false, and you must set ProcessStartInfo..::.RedirectStandardOutput to true. Otherwise, reading from the StandardOutput stream throws an exception
You would need to change your code a little bit to adjust for the changes:
Process myApp = new Process(#"C:\some\dirs\foo.exe", "someargs");
myApp.StartInfo.UseShellExecute = false;
myApp.StartInfo.RedirectStandardOutput = false;
myApp.Start();
string output = myApp.StandardOutput.ReadToEnd();
p.WaitForExit();
you could try setting processStartInfo.RedirectStandardOutput = true;
As noted above, you can use RedirectStandardOutput as here.
Another, dirtier way is something like
using (Process child = Process.Start
("cmd", #"/c C:\some\dirs\foo.exe someargs > somefilename"))
{
exeProcess.WaitForExit();
}
And then read its output from somefilename