RunAs and C# process - impersonate user credentials not working - c#

I want to create a simple application to launch another application under different credentials.
Both application are on my laptop which is not on the domain. I need to run SSMS using a domain user credentials.
When I use the following runas command, it works:
runas.exe /netonly /user:domain\username /password:mypass "C:\Program Files (x86)\Microsoft SQL Server\110\Tools\Binn\ManagementStudio\Ssms.exe"
The following code IS NOT working :
var file = #"C:\Program Files (x86)\Microsoft SQL Server\110\Tools\Binn\ManagementStudio\Ssms.exe";
var sspw = new SecureString();
foreach (var c in "mypass" sspw.AppendChar(c);
var proc = new Process();
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.WorkingDirectory = Path.GetDirectoryName(file);
proc.StartInfo.FileName = Path.GetFileName(file);
proc.StartInfo.Arguments = "";
proc.StartInfo.Domain = "domain";
proc.StartInfo.UserName = "username";
proc.StartInfo.Password = sspw;
proc.StartInfo.LoadUserProfile = true;
proc.Start();
The exception message is:
Logon failure: unknown user name or bad password

Related

Adding Credentials to diffrent account from local system account

Were using octopus for deployment, the tentacle is running as "local system account" I would like the tentacle to add credentials for a diffrent account. However I have no luck i doing so.
So far i tried creating a c# program which starts a new process as the other user, and the calls the cmdkey.exe
private static void CallCmdKey(string runAsDomain, string runsAsUser, string runAsPass, string target, string user, string pass)
{
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo.Arguments = $"/generic:{target} /user:{user} /pass:{pass}";
proc.StartInfo.FileName = Environment.GetEnvironmentVariable("WINDIR") + "\\system32\\cmdkey.exe";
Console.Out.WriteLine(proc.StartInfo.Arguments);
proc.StartInfo.Domain = runAsDomain;
proc.StartInfo.UserName = runsAsUser;
proc.StartInfo.LoadUserProfile = true;
SecureString sec = new SecureString();
runAsPass.ToCharArray().ToList().ForEach(sec.AppendChar);
proc.StartInfo.Password = sec;
proc.StartInfo.WorkingDirectory = ".";
proc.StartInfo.UseShellExecute = false;
proc.Start();
proc.WaitForExit();
Console.Out.WriteLine("done");
}
But it fails with access denied.
Then i tried power shell and psexec like this:
$psexec = "C:\temp\psexec.exe"
Invoke-Command -ScriptBlock{&$psexec -accepteula -u $WEB02AP2User -p $GISWEB02AP2Pass cmd /c cmdkey /generic:ffff /user:mufasa /pass:yoyo}
but it fails with
Access is denied.
PsExec could not start cmd:
The remote script failed with exit code 5
For security reasons Im not allowed to change account for the tentacle service
How can i sovle this issue
I Was unable to find a solutions to this issue. Only workaround was to let the octopusservice run as a specific user account

Execute .bat file on server F-drive from code behind

I have a .bat file on the servers F-drive which I wanna execute. The .bat file itself are calling another server and execute a .exe file. When I go in to the server and manually execute .bat it works fine. Now I wanna execute the .bat from C#.
I have tried several things.
1
ManagementClass management = new ManagementClass("Win32_Process");
var inParams = mprocess.GetMethodParameters("Create");
inParams["CommandLine"] = #"F:\Sysutv\Utils\StartnotepadTEST.bat";
inParams["CurrentDirectory"] = #"F:\Sysutv\Utils\";
mprocess.InvokeMethod("Create", inParams, null);
2
Process.Start(#"F:\Sysutv\Utils\StartnotepadTEST.bat");
3
ProcessStartInfo processInfo = new ProcessStartInfo("cmd.exe", #"/c start F:\Sysutv\Utils\StartnotepadTEST.bat");
ProcessStartInfo processInfo = new ProcessStartInfo(#"F:\Sysutv\Utils\StartnotepadTEST.bat");
ProcessStartInfo processInfo = new ProcessStartInfo(#"C:\test\test.bat");
processInfo.CreateNoWindow = true;
processInfo.UseShellExecute = false;
Process p = Process.Start(processInfo);
This is not working. How can I start that file that is on the server (from the server)?
The .bat file:
start F:\Sysutv\Utils\psexec.exe \\serverName -u login -p password -i C:\Windows\notepad.exe

appcmd.exe Cannot read configuration file due to insufficient permissions

I have followed the steps at Cannot read configuration file due to insufficient permissions
I also tried to manually set the rights to related files, but that didn't work, especially on appcmd.exe.
I am trying to update applicationHost.config to set IIS reset time dynamically, when my website loads on IIS. For this I am trying to execute the following code in global.asax file of my project:
string WindowsDir = Server.MapPath("~/Startup");
string command = WindowsDir + #"\Startup.cmd";
string outputFilePath = WindowsDir + #"\log.txt";
string arguments = String.Format(
"/c echo Startup task (Startup.cmd) executed at {0} >>\"{1}\"",
System.DateTime.UtcNow.ToString(),
outputFilePath);
// System.Diagnostics.Process.Start(command, arguments);
System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
startInfo.FileName = command;
startInfo.Arguments = arguments;
process.StartInfo = startInfo;
process.Start();
This works perfectly when I run my website in Visual Studio, but when I deploy it on IIS, it produces the following errors:
Prevent the IIS app pools from shutting down due to being idle:
appcmd set config -section:applicationPools -applicationPoolDefaults.processModel.idleTimeout:00:00:00 /commit:apphost
ERROR ( message:Configuration error
Filename: redirection.config
Line Number: 0
Description: Cannot read configuration file due to insufficient permissions. )
Schedule IIS app pool recycles for 8:00 AM UTC time (1:00 AM MST):
appcmd set config -section:applicationPools -applicationPoolDefaults.recycling.periodicRestart.schedule.[value='08:00:00']" /commit:apphost
ERROR ( message:Configuration error Filename: redirection.config
Line Number: 0
Description: Cannot read configuration file due to insufficient permissions. )
Prevent IIS app pool recycles from recycling on the default schedule of 1740 minutes (29 hours):
appcmd set config -section:applicationPools -applicationPoolDefaults.recycling.periodicRestart.time:00:00:00 /commit:apphost
ERROR ( message:Configuration error
Filename: redirection.config
Line Number: 0
Description: Cannot read configuration file due to insufficient permissions. )
Then I tried to execute following code:
string WindowsDir = Server.MapPath("~/Startup");
string command = WindowsDir + #"\Startup.cmd";
string outputFilePath = WindowsDir + #"\log.txt";
string arguments = String.Format(
"/c echo Startup task (Startup.cmd) executed at {0} >>\"{1}\"",
System.DateTime.UtcNow.ToString(),
outputFilePath);
// System.Diagnostics.Process.Start(command, arguments);
var process = new System.Diagnostics.Process();
var startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
startInfo.FileName = command;
startInfo.Arguments = arguments;
string name = "Administrator";
string pass = "password";
startInfo.Password = pass.Aggregate(new System.Security.SecureString(), (ss, c) => { ss.AppendChar(c); return ss; });
startInfo.UserName = name;
startInfo.UseShellExecute = false;
startInfo.RedirectStandardOutput = true;
process.StartInfo = startInfo;
process.Start();
Then it didn't work even from Visual Studio. I then reverted back to code that was working in Visual Studio (as mentioned above). And added the following tags in Web.config (inside <system.web> tag):
<authentication mode="Windows"/>
<identity impersonate="true" userName="Administrator" password="password"/>
But that didn't work when I ran the website on IIS (7.5). Any ideas how to make this work?
I had the same problem (I was using IIS 8, Windows 8, C#, VS 2013), by code sometimes you have'not permissions. I was executing:
string windir = Environment.GetEnvironmentVariable("windir");
string comando = windir +"\\System32\\inetsrv\\appcmd.exe set site /site.name:test /+bindings.[protocol='http',bindingInformation='*:80:mitest']";
System.Diagnostics.ProcessStartInfo procStartInfo = new System.Diagnostics.ProcessStartInfo("cmd", "/c " + comando);
And I get the Error: "Cannot read configuration file due to insufficient permissions"
At the end use the ServerManager class, first I reference this dll in my project:
C:\Windows\System32\inetsrv\Microsoft.Web.Administration.dll
then I use the code to manipulate the AppPools, Sites or Bindings:
using (ServerManager serverManager = new ServerManager())
{
if (serverManager.ApplicationPools == null)
return;
for (int i = 0; i < serverManager.Sites.Count; i++)
{
Microsoft.Web.Administration.ApplicationPoolCollection appPoolCollection = serverManager.ApplicationPools[i];
}
if (serverManager.Sites == null)
return;
for (int i = 0; i < serverManager.Sites.Count; i++)
{
Microsoft.Web.Administration.BindingCollection bindingCollection = serverManager.Sites[i].Bindings;
}
}

connect compmgmnt.msc to remote host using c#

how can i use compmgmnt.msc to remote host using c#.
i found this...
execute this command in "cmd.exe" it is working and ask you for The password:
/user:administrator \"mmc.exe compmgmt.msc /computer:IZADI-PC\
but i need to know how can i use this command in c#.
i also need to pass the password to this command using c#.
i have username and password of the remote computer and i wanna do everything programatically.
I also visited :
http://www.lansweeper.com/forum/yaf_postst5116_Runas-Custom-Actions.aspx
Process.Start with different credentials with UAC on
Thank you in advanced!!!
anyone write sample code to excecute /user:administrator \"mmc.exe compmgmt.msc /computer:IZADI-PC\ in c#
ProcessStartInfo startInfo = new ProcessStartInfo();
Process myprocess = new Process();
myprocess.StartInfo.CreateNoWindow = true;
myprocess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
myprocess.StartInfo.UseShellExecute = false;
myprocess.StartInfo.Verb = "runas";
myprocess.StartInfo.FileName = "cmd.exe";
myprocess.StartInfo.UserName = "administrator";
myprocess.StartInfo.Password = MakeSecureString("123456");
myprocess.StartInfo.Arguments = "/k mmc.exe compmgmt.msc /computer:PC135-PC";
myprocess.Start();
myprocess.Close();

Ensuring Process.Start() runs under the logged in user

I'm running a batch file from some ASP.NET/C# code on a web server. Basically the batch file performs some test automation tasks on a VM using tools like psloggedon and pexec.
If I run the batch file manually when I'm logged into the server under an administrative account, it works fine.
My problem comes when I run it from my code (below), it seems to run under the 'SYSTEM' account, and psloggedon etc. don't seem to work correctly.
Code
Process p = new Process();
p.StartInfo.FileName = "C:\SetupVM.bat";
p.Start();
p.WaitForExit();
I've got this in my web.config, it doesn't seem to make any differance?
<identity impersonate="true" userName="Administrator" password="myadminpassword"/>
Is there anyway I can ensure the batch file runs under the 'Administrator' account?
UPDATED CODE
Process p = new Process();
p.StartInfo.FileName = "C:\\SetupVM.bat";
p.StartInfo.UserName = "Administrator";
p.StartInfo.UseShellExecute = false;
p.StartInfo.WorkingDirectory = "C:\\";
string prePassword = "myadminpassword";
SecureString passwordSecure = new SecureString();
char[] passwordChars = prePassword.ToCharArray();
foreach (char c in passwordChars)
{
passwordSecure.AppendChar(c);
}
p.StartInfo.Password = passwordSecure;
p.Start();
p.WaitForExit();
From MSDN:
When UseShellExecute is false, you can start only executables with the Process component.
Maybe this is the issue as I'm trying to run a .bat file?
Thanks.
You can provide the username and password to the StartInfo:
Process p = new Process();
p.StartInfo.FileName = "C:\SetupVM.bat";
p.StartInfo.UserName = "Administrator";
p.StartInfo.Password = "AdminPassword";
p.Start();
p.WaitForExit();
See the documentation for ProcessStartInfo.

Categories

Resources