RDP into multiple win 10 computers from c# - c#

I am attempting to login into multiple win 10 computers via rdp from a list of computer names then reboot them. From my best knowledge rdp is the way to do this. I am in the beginning stages and I am not able to even connect one machine.
I have attempted and tested code from every resource I could find. I have tested the multiple Microsoft RDP Client Control versions and verified I have version 10 on my Windows 10 Machine. Below is the code I have so far.
private void startBtn_Click(object sender, EventArgs e)
{
try
{
dmain = #"MGROUPNET\";
lines = listBox.Lines;
Server = lines[0];
dmain = dmain + nUser;
//Testing to verify correct details
usernameLabel.Text = dmain;
passLabel.Text = nPass;
serverLabel.Text = Server;
rdp1.Server = Server;
rdp1.UserName = dmain;
rdp1.AdvancedSettings9.NegotiateSecurityLayer = true;
rdp1.AdvancedSettings8.ClearTextPassword = nPass;
rdp1.Connect();
connectLabel.Text = this.rdp1.Connected.ToString();
}
catch (Exception Ex)
{
MessageBox.Show("Error Disconnecting: " + Ex);
}
}
After this code, I get a connection status of 2. This then changes to 0 without displaying anything. Any help or guidance would be appreciated.

I suggest you to use PsExec instead of RDP. You can download it from here:
https://learn.microsoft.com/en-us/sysinternals/downloads/psexec
Now, all you have to do is just open a cmd window with your c# program with the following command:
psexec_path \\target_IPv4 -u local_username -p password shutdown.exe -t 0 -r
If connection is succeed, the device will try restart with the specified user credentials. Make sure that the user has the required permissions to do this (e.g. if you are in a domain).
I have to notice that the connection connection is not secured. Use PsExec v2.1 at least to encrypt your connection.

Related

C# Windows form Application With PowerShell Automation Commands Restrictions

I am trying to create an app that would setup bitlocker PIN Programmatically.
the app works as well as the PowerShell Command, However, I am unfortunately unable to execute it.
I am getting the following Error when Executing:
"Application Attempted to perform an operation not allowed by the security policy. To grant this application the required permissions, contact your system administrator or use Microsoft .Net Configuration Tool"
private void Submit_Click(object sender, EventArgs e)
{
if (PIN.Text.Length < 20)
{
MessageBox.Show("Passwords must be at least 20 characters long.");
return;
}
else if (PIN2.Text != PIN.Text)
{
MessageBox.Show("Password & Confirmation are not identical, Please ensure that both Passwords are the same");
return;
}
else
{
PowerShell ps = PowerShell.Create();
ps.AddCommand("$PIN = \"" + PIN.Text + "\" | ConvertTo-SecureString -AsPlainText -Force; Enable-BitLocker -MountPoint \"C:\" -PIN $PIN -TPMAndPinProtector -SkipHardwareTest");
ps.Invoke();
MessageBox.Show("Your Pre-Boot PIN has now been Setup - Please reboot after 30 Minutes and login with your PIN");
Application.Exit();
I have set assembly: SecurityRules(SecurityRuleSet.Level1) but issue remains.
is it a GPO that would need to be amended at all? or would i be able to bypass in the App somehow?
Have you tried making an actual PowerShell script file and then running the file?
take a look at this

Unable to connect to PostgreSQL server via SSH: No connection could be made because the target machine actively refused it

I am trying to automatically create an SSH connection for a program that uses an SSH tunnel to update a local database from a remote PostgreSQL server. Up to this time, I have been manually opening a tunnel with PuTTY (including local port forwarding instructions with the -L command). I want to use ssh.net to automatically open the port when the program is run. Once the connection is made, the program uses Entity Framework Core to access the remote database.
When I open the SSH connection with PuTTY, the program runs fine. This is the PuTTY command:
//plink.exe -i "C:\Users\user.name\Desktop\host_private_key.ppk" -L 6544:111.22.33.66:6543 -N user#address.io -pw *PASSWORD*"
(login details removed for privacy)
This is the ssh.net code that I have trying to open the same connection:
public void MakeSSHTunnel()
{
string password = "password";
// path of RSA private key in openSSH format:
string privateKeyPath = "C:/Users/user.name/.ssh/id_rsa";
try
{
// creates variable to transmit RSA private key + passphrase to server via SSH.NET, openSSH compatible.
var privateKeyFile = new PrivateKeyFile(privateKeyPath, password);
string serverAddress = "address.io";
string user = "user";
// allows for the remote port forwarding options required by the server
using (var client = new SshClient(serverAddress, user, privateKeyFile))
{
client.Connect();
var tunnel = new ForwardedPortLocal(6544, "111.22.33.66", 6543);
client.AddForwardedPort(tunnel);
// testing weather the connection has been successful:
if (client.IsConnected)
{
Console.WriteLine("OPENTUNNEL.CS: Connection to {0} successful.", serverAddress);
state = "Open";
}
else
{
Console.WriteLine("Connection to {0} failed.");
state = "Closed";
}
tunnel.Exception += delegate (object sender, ExceptionEventArgs e)
{
Console.WriteLine(e.Exception.ToString());
};
tunnel.Start();
Program.RunBackup();
// ... closes the port ... //
tunnel.Stop();
client.Disconnect();
}
}
catch (UnauthorizedAccessException e)
{
Console.WriteLine(e);
}
}
I am confused since in the above, the if (client.IsConnected) returns true.
The error seems to be occurring when the Entity Framework Core OnConfiguring() method passes details of the connection with its optionsBuilder:
optionsBuilder.UseNpgsql($"Host=127.0.0.1;Port=6544;Database=user;Username=user;Password=databasePassworh;CommandTimeout=300;Timeout=300;SSL Mode=Require;Trust Server Certificate=true;Convert Infinity DateTime=true");
The errors that are arising are:
NpgsqlException: Exception while connecting
and:
ExtendedSocketException: No connection could be made because the target machine actively refused it. 127.0.0.1:6544
I have double checked all passwords, and read through all the SSH.NET documentation and code examples, and left all the previously working (via PuTTY) code untouched.
If anyone can see what I'm doing wrong, I would be grateful. C#, SSH.NET and port forwarding are new to me, please tell me where I'm being an idiot.
This code is now working. I believe the problem was that in line:
var tunnel = new ForwardedPortLocal(6544, "111.22.33.66", 6543);
the 'bound port' did not include an address. I had seen examples where this was undefined, and had followed these. On stepping through the code, I noticed that the field was blank, and decided to try 127.0.0.1. This is now successfully connecting to the database. It works with:
var tunnel = new ForwardedPortLocal("127.0.0.1", 6544, "111.22.33.66", 6543);
Thanks for looking into this and for your contributions.

SSH Connection via C#

This is the situation. I have a Windows machine and a Linux machine. There is a shared drive between these two machines (which is mapped to Q:). I am trying to figure out how to create an SSH session at the Q: drive (shared drive) from C#. I am trying to use the SharpSsh library to do this.
This is what I have so far, however, it is giving me an error:
try
{
ssh = new SshStream(host, username, password);
Console.WriteLine("OK ({0}/{1})", ssh.Cipher, ssh.Mac);
Console.WriteLine("Server version={0}, Client version={1}", ssh.ServerVersion, ssh.ClientVersion);
Console.WriteLine("-Use the 'exit' command to disconnect.");
Console.WriteLine();
//Sets the end of response character
ssh.Prompt = "#";
//Remove terminal emulation characters
ssh.RemoveTerminalEmulationCharacters = true;
//Reads the initial response from the SSH stream
Console.Write(ssh.ReadResponse()); // Blocking here
while (true)
{
string command = Console.ReadLine();
if (command.ToLower().Equals("exit"))
break;
//Write command to the SSH stream
ssh.Write(command);
//Read response from the SSH stream
Console.Write(ssh.ReadResponse());
}
}
catch(Exception e)
{
Console.WriteLine(e.Message);
}
if(ssh != null)
{
ssh.Close();
}
I have added the Tamir.SharpSSH.dll as a reference to the project, and I am using it in the project. There are two other dll's that are included with SharpSSH, do I need to add them as well to the references? The examples I have seen only have the Tamir.SharpSSH.dll as a reference.
I am not sure how to initiate the connection in the correct location, and how to submit commands properly to the ssh.
UPDATE
I realized I needed to close the SSH connection before ending the program. The error does not exist anymore, however, I am still not getting any information from my "ls" command.
UPDATE
I updated the code with what I have now. It seems like the ssh.ReadResponse() is blocking, which leads me to believe the server is not responding. Is that correct?

FtpWebRequest WebException: "Unable to connect to the remote server"

I have code in a Windows Service that successfully connects to an FTP server when I run it locally through a test harness (with the FTP server being on another machine on the local network).
When I install it in the production hosting environment, though, I get the dreaded WebException "Unable to connect to the remote server". It doesn't seem to matter whether I'm using ACTV or PASV FTP, all I get it this WebException. If I try to FTP from the Windows command line, however, it works perfectly well (so it's not the firewall at fault).
The code I'm using (adapted from How to List Directory Contents with FTP in C#?) reads:
private static readonly string __ftpSourceServer = "ftp://"
+ ConfigurationManager.AppSettings["FtpServer"] + "/";
private static readonly NetworkCredential __ftpCreds = new NetworkCredential(
ConfigurationManager.AppSettings["Username"],
ConfigurationManager.AppSettings["Password"]);
// And now the method MediaSyncDaemon.GetFilesToFetch:
bool usePassive = Boolean.TryParse(ConfigurationManager.AppSettings["UsePassive"]
, out usePassive) && usePassive;
Uri ftpSrv = new Uri(__ftpSourceServer + Uri.EscapeUriString(
ConfigurationManager.AppSettings["FtpPath"]));
Logger.Debug("Connecting to FTP server at " + ftpSrv + "; PASV? " + usePassive);
FtpWebRequest listRequest = (FtpWebRequest) WebRequest.Create(ftpSrv);
listRequest.Method = WebRequestMethods.Ftp.ListDirectory;
listRequest.Credentials = __ftpCreds;
listRequest.UsePassive = usePassive;
listRequest.UseBinary = false;
using (FtpWebResponse listResponse = (FtpWebResponse) listRequest.GetResponse())
{
// ReSharper disable AssignNullToNotNullAttribute
return new StreamReader(listResponse.GetResponseStream())
.ReadToEnd().Split(new[] { '\n', '\r' },
StringSplitOptions.RemoveEmptyEntries)
.Where(s => s.EndsWith(".zip", true, CultureInfo.InvariantCulture))
.ToList();
// ReSharper restore AssignNullToNotNullAttribute
}
The exception is thrown at the FtpWebRequest.GetResponse() call in the using line (outside the return statement), with nothing else in the stack trace:
System.Net.WebException: Unable to connect to the remote server
   at System.Net.FtpWebRequest.GetResponse()
   at (that line number in that file)
The only real difference between my test harness (which works) and the production environment (which doesn't) is the presence of a firewall in the production environment — all four servers are on slightly different subnets:
Dev client 10.16.6.155 subnet 255.255.255.128
Dev server 10.16.7.242 subnet 255.255.255.0
Prod client 192.168.102.107 subnet 255.255.255.0
Prod server 192.168.203.110 subnet 255.255.255.0
but the firewall can't be the problem is I can FTP from Prod client to Prod server interactively, just not programmatically.
I've tried changing the bool appSettings value for UsePassive and that makes no difference and, in every case, nothing shows up in the FTP server log (so it's not getting that far).
Now I'm not expecting anyone to be able to debug the hardware infrastructure of my hosting environment, but I'm struggling to think of what else I could vary to get this to work. I've seen it work locally in my test harness, calling the same method. In case it helps, the test harness code reads as follows:
[NUnit.Framework.Test]
public void FtpFileListTest()
{
ICollection<string> files = MediaSyncDaemon.GetFilesToFetch();
Assert.IsNotNull(files);
Assert.Greater(files.Count, 0);
}
Does anyone have any ideas of what else I could try, please?
Thanks!
Update
Having had some suggestions of places to look in the comments, I can update this a little further:
The problem does not appear to be user permissions — the service is running in the context of the Local System account (which has more permissions than Administrator does)
The problem does not appear to be code-access security. I've added a SocketPermission.Demand call to the entry method for this chunk of code:
System.Security.CodeAccessPermission socketPermission;
socketPermission = new SocketPermission(NetworkAccess.Connect,
TransportType.Tcp, ConfigurationManager.AppSettings["FtpServer"], 20);
socketPermission.Demand();
socketPermission = new SocketPermission(NetworkAccess.Connect,
TransportType.Tcp, ConfigurationManager.AppSettings["FtpServer"], 21);
socketPermission.Demand();
And I'm not seeing any SecurityException being thrown as a result; I'm still getting the same WebException, at the new line number for that same code position.
Does anyone have any further suggestions of what I could try?
I would like to share our problem and solution:
We were not able to connect to the FTP server with ftpwebrequest on a corporative PC, but on ours it would work fine.
The issue was that ftpwebrequest() was grabbing the proxy configuration that the company’s IT forces on the PC.
To resolve this issue, we added (ftpwebrequest object).proxy = null; before connecting.

How to give IIS AppPool Desktop Rights

The action I need help about, is to execute a EXE file on own servers disk from a intranet-webpage, which IIS are on same server-installation. The webpage use a business layer to execute a ProcessStart together with given parameters.
When I perform the execution from web, the taskmanager show me that the application are starting up with the IIS AppPool of webpage as user. Few seconds later it's killed. In my database logs, I can see;
The Microsoft Jet database engine cannot open the file '\\computer\pathfile.ext'. It is already opened exclusively by another user, or you need permission to view its data.
That's correct. The EXE tool are, in turn, loading files from other computers. This is a special behavior which are well studied and well working while using the tool from desktop.
My goal/question,
I want this web-function-call behave with desktop rights. Is it possible at all?
The IIS AppPool have a regular setup with account ApplicationPoolIdentity. I appeared to be "lucky unwise", without knowledge about how much IIS 7.5 and Windows Server 2008 R2 raised the security model since <=IIS6.
I tried to change the app-pool user to NetworkService, Administrator.
I tried to set the application with app-pool as exec/read right
I even tried to let webapp to run a batch-file with a call to application inside..
Then I was begin to change the ProcessStart-behavior. And here, I
don't know much of what to do. I tried to add VERB runas. Force a
password prompt is not a solution here. I tried to simulate a
username/password. No luck there. I also tried to add runas /user:
blabla as parameters with ProcessStart, after used /savecred in a
desktop command window once. No luck there.
Maybe this should work but I just don't understand the correct setup of properties. I add the ProcessStart code snippet below, also added some commented code to let you see what I tried.
public string RunProcess(ApplicationType type, int param)
{
currentSelection = GetApplicationType(type);
ProcessStartInfo info = new ProcessStartInfo(currentSelection.Path);
info.CreateNoWindow = false;
info.UseShellExecute = true;
//info.UseShellExecute = false;
//info.ErrorDialog = false;
//info.UserName = "dummyUsEr";
//info.Password = this.SecurePwd("DummyPWd");
info.WindowStyle = ProcessWindowStyle.Normal;
info.Arguments = string.Format(" {0}", param.ToString());
using (Process exec = Process.Start(info))
{
try
{
exec.WaitForExit();
}
catch
{
}
}
return output;
}
EDIT
Just to be clear, and perhaps help some another guy/girl browsing to this question, I attach the snippet of Password-generation,
protected System.Security.SecureString SecurePwd(string pwd)
{
SecureString securePwd = new SecureString();
foreach (char ch in pwd.ToCharArray())
securePwd.AppendChar(ch);
return securePwd;
}
I see that you've tried putting in a specific username and password for the process start impersonation, but you say that the process accesses files on another computer and I don't see any mention of specifying a domain name which presumably you would need to access remote files?
So like this:
info.Domain = "domainname";
info.UserName = "dummyUsEr";
info.Password = "DummyPWd";
Also, what does this.SecurePwd() do and have you tried it with just the straight password string that you're passing into it?

Categories