C# admin rights with credentials - c#

after reading all topic about C# runas issues, i still can't find my solution.
My problem here is simple, i'm on a user session with no rights and i want to execute an exe as Admin.
I tried many things like:
var psi = new ProcessStartInfo
{
FileName = "isauq.exe",
UserName = "user",
Domain = "",
Password = pass,
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true
};
Process.Start(psi);
With the password as an AppendChild for each characters.
I have the admin credentials but seems like the UAC prompt is still popping up
Is there any solutions in C# or Bat ? Or any solution to automate the user entries in UAC prompt ?
Thanks for your time.

Related

C# EFS, Windows Encrypt Or Dycrypt Fails when Impersonated

I need to write a file while impersonated as another user John (Member of administrator).
What happens:
File is written and created, then all Access Control is removed and added (Full Control).
No matter where in this process i try to Encrypt file access is denied
using FileOptions
Using File.Encrypt.
my worked around to at least encrypt was with opening another impersonation later on.
But No matter what i do, i can't Decrypt or even read the encrypted Text file.
If file is encrypted reading or decrypting fails, even though i can read or write just fine while impersonated.
In some scenarios Everything works fine, But after a system restart or logout, again fails with access denied.
For impersonation i used this answers Impersonation
using (impersonate = new ImpersonateUser(ImpersonationType.WinIdentity, Domain, User, SecurePassword))
{
System.Diagnostics.Debug.WriteLine($"Before Impersonation: {Environment.UserName}");
done = impersonate.RunImpersonated(() =>
{
System.Diagnostics.Debug.WriteLine($"After Impersonation: {Environment.UserName}");
//if (Util.IsWindowsEncrypted(ConfigFullPath)) File.Decrypt(ConfigFullPath);
var json = File.ReadAllText(ConfigFullPath);
var configFile_data = SerializationUtil.Deserialize<Config>(json);
//if (!Util.IsWindowsEncrypted(ConfigFullPath)) File.Encrypt(ConfigFullPath);
});
}
A working repository to reproduce is available here Repository containing full sample,
See CreateConfig or ReadConfig method in Config.cs
(if you were able to create and read a encrypted file, check if after
restart it is the same)
A Workaround i just found was to create a Process before doing any impersonation.
using (Process cmd = new Process())
{
ProcessStartInfo startInfo = new ProcessStartInfo
{
FileName = "cmd.exe",
Arguments = $"/c",
UseShellExecute = false,
UserName = user,
Password = pass,
LoadUserProfile = true
};
cmd.StartInfo = startInfo;
cmd.Start();
}

Printing a PDF from ASP .Net (c#) using Acrobat Reader

I am trying to print a PDF using ASP (C#) through Adobe Reader -the problem is it does work on my local machine but not on server. On my local it starts Adob eReader in minimized state and I can see the file present inside Printer's "See what's printing" window. But on the server I can see the process has started from Task Manager but there's no UI visible as well no file in printer's list.
I though it may be a permission issue but after trying the following steps - it still does not work.
What I have tried.
As by default it runs under DefaultAppPool user - so I created a new App pool under the admin user, it now starts the process under admin but still I can't see the UI and no output on printer.
I added permission "Allow service to interact with desktop" to IIS Admin Service following this article https://support.microsoft.com/en-us/help/555134 - but no difference.
My current code
string args = string.Format("/s /o /h /t \"{0}\" \"{1}\"", filepath, printerName);
var startInfo = new ProcessStartInfo {
FileName = Properties.Settings.Default.AdobeReaderPath,
Arguments = args,
CreateNoWindow = true,
ErrorDialog = false,
UseShellExecute = false,
Verb = "print",
WindowStyle = ProcessWindowStyle.Minimized,
RedirectStandardInput = true,
RedirectStandardOutput = true
};
var process = Process.Start(startInfo);
In the Application Pool Advanced settings, make sure you set the option
"Load User Profile" to True on the server.

How to pass hidden input to another program in C#

I have been having trouble passing input programmatically to the system net user program using C#. I am trying to activate and set a password for a certain user account. By my investigations, it seems like the process finishes before anything can be passed. I do not know why the background net user program does not wait for input before exiting.
Here is the command I am running programmatically to accomplish this:
net user username /active:yes & net user username *
The output of the second command is as follows:
Type a password for the user:
Retype the password to confirm:
The command completed successfully
If you were to run the above command manually, it would ask you for the password and hide what you're typing from the screen. However, the program doesn't seem to stop when ran programmatically.
To call the program, I have a function that starts the program and returns the process to another function, which sends input to the process. Here is the first function:
static Process RunCommandGetProcess(string command)
{
Process process = new Process();
ProcessStartInfo psInfo = new ProcessStartInfo();
psInfo.FileName = "CMD.exe";
psInfo.Arguments = "/C " + command + "& PAUSE";
// Allow for Input redirection
psInfo.UseShellExecute = false;
psInfo.RedirectStandardInput = true;
// Window style
psInfo.WindowStyle = ProcessWindowStyle.Normal;
// Start the mothertrucker!
process.StartInfo = psInfo;
process.Start();
return process;
}
And the Calling function:
static int ActivateUserWithPassword(string password)
{
// Start net user with that other function
Process process = RunCommandGetProcess("net user username /active:yes & net user username *");
StreamWriter streamWriter = process.StandardInput;
streamWriter.WriteLine(password); // First Prompt
streamWriter.WriteLine(password); // Second Prompt
process.WaitForExit();
return process.ExitCode;
}
However, When I run the debugger, the commands complete successfully before the two streamWriter.WriteLine(password); lines are even met! I have tried Googling, but came to no avail.
You people are my only hope.
Okay! I have been highly motivated to solve your issue as soon as i saw it!. after 2 hours of non-stop debugging, i have a solution for you!.
Issue No .1 : Your application does not have Administrator privileges, that is why the command exits right after you start. Start the .exe with Admin Privileges.
Issue No. 2 : Since the password is masked in the input, Even if i did a streamWriter.WriteLine(password) once,The output is "Command Executed Successfully". There is no way of knowing if the password was actually passed or it took empty string as the password.
Solution
You can use the net user command with a parameter for password like this
net user user_name password. No need to prompt the user for password i.e Don't use '*' after username ,since you are passing it through the program.
So this is how it works
Process proc = new Process();
ProcessStartInfo start = new ProcessStartInfo();
start.FileName = "cmd";
start.Arguments = "/k";
start.RedirectStandardInput = true;
start.WorkingDirectory = Environment.CurrentDirectory;
start.UseShellExecute = false;
proc.StartInfo = start;
proc.Start();
proc.StandardInput.WriteLine("net user \"username\" password");
Very Very Important!!
Start the exe as an administrator OR you will have to do this
start.UseShellExecute = true;
start.Verb = "runas";
But then you wont be able to redirect the Output/Input streams!.

Open Excel from a WebAPI service hosted in local IIS

I'm facing a strange problem with the IIS Local. I've developed a webapi Controller that, at some point, opens Excel, makes some processing with macros and then closes. Here's the piece of code that opens Excel with several parameters:
var procStartInfo = new ProcessStartInfo(
this.Parameters[ConsoleExecutionParameters.FileToExecute],
this.ParametersProcessed)
{
CreateNoWindow = false,
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
RedirectStandardInput = true,
WindowStyle = ProcessWindowStyle.Maximized,
WorkingDirectory = workingDirectory
};
using (var proc = new Process { StartInfo = procStartInfo })
{
try
{
proc.EnableRaisingEvents = true;
proc.Start();
proc.WaitForExit(60000);
proc.StandardInput.Flush();
if (!proc.HasExited)
....
Gotta say that this piece of code WORKS (and opens the excel correctly) if the WebAPI is run under IIS Express. However, when running it under a local IIS, an Excel process is opened (at least it is shown in the task manager) but no Excel window appears, the application seems to hang when "proc.WaitForExit" instruction is called, and EXCEL.EXE process stays like in a "zombie" state. After some time (60 seconds) my application times out and the Excel.EXE process is still hung.
Does someone have any idea about why it works on IIS express and doesn't in Local IIS?
Thanks and kind regards.

Executing batch file in WCF

I am trying to execute a batch file server-side in IIS to add a printer using the printuientry call.
The problem I am facing is that I am using the Copy To Output Directory - Copy Always and the following code:
var path = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
var processInfo = new ProcessStartInfo(Path.Combine(path, "AddPrinter.bat"))
{
CreateNoWindow = true,
UseShellExecute = false,
WorkingDirectory = path,
Arguments = ipAddress,
RedirectStandardError = true,
RedirectStandardInput = true,
RedirectStandardOutput = true
};
var process = Process.Start(processInfo);
process.WaitForExit(10000);
process.Close();
Now when deugging, I have checked the values of path and its set to
file:\C:\_Projects\PrinterServerV2\bin
and I have checked to see if the file and directory exist which they do.
But I get the exception:
System.ComponentModel.Win32Exception (0x80004005): The directory name is invalid
Any ideas please??
Check if the user you had set in the iis configuration does have all privileges to run, access, write and read what you wanna do with your batch file.
Also try to change your ProcessStartInfo like the process will be cmd.exe and your batch file the argument.
I had a similar issue How to execute multiples .BAT files in C#
try AppDomain.CurrentDomain.BaseDirectory as path.

Categories

Resources