Failed to impersonate domain user via C# - c#

I am trying to impersonate remote admin user so that i can perform modifications on the files present on remote Linux machine. But i get error message as Access to the path is denied.
However this thing manually i am able to do via putty using command :
sudo -S -u wtsnqa rm /path-to-file/
Any help is worth appreciable.
My code :
SessionOptions sessionOptions = new SessionOptions
{
Protocol = Protocol.Sftp,
HostName = "sj1slm612",
UserName = "userid",
Password = "password",
SshHostKeyFingerprint = "ssh-rsa 2048 fa:e9:58:24:1b:41:a3:15:63:0d:c0:72:41:5d:51:7a"
};
using (Session session = new Session())
{
// Connect
session.Open(sessionOptions);
// Performing removing files from remote server via impersonation.......
AppDomain.CurrentDomain.SetPrincipalPolicy(System.Security.Principal.PrincipalPolicy.WindowsPrincipal);
using (WindowsIdentity Authorized_user = new WindowsIdentity("wtsnqa"))
{
using (WindowsImpersonationContext context = Authorized_user.Impersonate())
{
File.Delete(#"\\sj1slm612\apps\instances\express_13000\configuration\standalone-full.xml");
File.Delete(#"\\sj1slm612\apps\instances\query_13100\configuration\standalone-full.xml");
File.Delete(#"\\sj1slm612\apps\instances\wppapi_13200\configuration\standalone-full.xml");
File.Delete(#"\\sj1slm612\apps\instances\wppgui_13300\configuration\standalone-full.xml");
Console.WriteLine("All config files removed from sj1slm612");
Console.ReadLine();
context.Undo();
}

Related

Copy files to AWS Windows server

Need to copy few files from aws Linux server to aws Windows server
added the inbound rule for ssh with port 22, in the security group of the Windows server
tried to connect that aws Windows using WinSCP, with username, pwd & the pem key file and connection failed.
also tried with below c# code with Renci.SshNet package from the Nuget.
using Renci.SshNet;
public static void CopyFileNew()
{
string host = #"ec2-11-11-11-11.us-east-1.compute.amazonaws.com";
string username = "username";
string password = #"pwd#2021";
PrivateKeyFile keyFile = new PrivateKeyFile(#"D:\keys\windows-key.pem");
var keyFiles = new[] { keyFile };
var methods = new List<AuthenticationMethod>();
methods.Add(new PasswordAuthenticationMethod(username, password));
methods.Add(new PrivateKeyAuthenticationMethod(username, keyFiles));
string remoteDirectory = #"\\ec2-11-11-11-11.us-east-1.compute.amazonaws.com\Data";
ConnectionInfo con = new ConnectionInfo(host, 22, username, methods.ToArray());
using (ScpClient scp = new ScpClient(con))
{
try
{
scp.Connect();
scp.Upload(new FileInfo(#"D:\temp\sample.txt"), #"E:\Export\test");
scp.Disconnect();
}
catch (Exception e)
{
Console.WriteLine("An exception has been caught " + e.ToString());
}
}
}
using tnc from powershell to port 22 --> got failed
using tnc from powershell to port 3389 --> got successful
Why can't you push the files to S3 from Linux machine and then pull them from S3 on Windows machine?
On Source machnie
aws s3 sync <local folder> s3://<transfer-bucket>
On Target machine
aws s3 sync s3://<transfer-bucket> <local folder>

Certificate Issues while connecting to Amazon S3

My C# code is trying to pull some files from an Amazon S3 bucket. This code works fine on my development as well as on UAT server. However, when I run this on my production server, I get a certificate error.
One difference between the UAT and Production servers is that on UAT there is no restriction on outbound internet access. On Production servers free outbound internet access is not allowed. we open only selective URLs as per requirements.
We have already opened access to s3.amazonaws.com. We have also ensured that this access works fine using WinSCP tool. However, when my code tries to do the same, I get the following error:
WinSCP.SessionRemoteException: Server Certificate Verification Failed: Issuer is not trusted.
The source code is attached below:
s3HostName = Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["s3HostName"]);
s3UserName = Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["s3UserName"]);
s3Password = Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["s3Password"]);
LocalFilePath = Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["LocalFilePath"]);
s3Folder = Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["s3Folder"]);
LocalFileFolder = Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["LocalFileFolder"]);
LocalFolder = LocalFilePath + yesterday + "\\";
SessionOptions sessionOptions = new SessionOptions
{
Protocol = Protocol.S3,
HostName = s3HostName,
UserName = s3UserName,
Password = s3Password,
};
TransferOptions transferOptions = new TransferOptions();
transferOptions.TransferMode = WinSCP.TransferMode.Automatic;
transferOptions.FilePermissions = null;
transferOptions.PreserveTimestamp = false;
using (Session session = new Session())
{
log.Debug("Open session for s3");
session.Open(sessionOptions);
if (!Directory.Exists(LocalFolder))
{
Directory.CreateDirectory(LocalFolder);
}
//to download files
session.GetFiles(s3Folder + "*" + yesterday + ".csv", LocalFolder);
session.Close();
log.Debug("Closed session for s3");
return "Success";
}
Resolved the issue using the oldest trick in the book. Reinstalled WinSCP. Its all working fine now.

How to download files from FTPS in C#

Our IT department gave me credentials for an FTPS, which I can access using FileZilla
But I also need to access the FTPS using an application I am working on to automate the process. The information provided to me was,
That this is an FTP over TLS/SSL
IP: xxx.xxx.xx.xx
Port: 990 <-- suggesting its an implicit encryption
UserName: username.ftp
Password: password123
After reading some posts on WinSCP on stack and their documentation, I still can't access the ftps using my application. My code so far..
SessionOptions sessionOp = new SessionOptions()
{
FtpSecure = FtpSecure.Implicit,
Protocol = Protocol.Ftp,
HostName = IP,
UserName = userName,
Password = password,
};
sessionOp.AddRawSettings("ProxyMethod", "3");
sessionOp.AddRawSettings("ProxyPort", "990");
using (Session session = new Session())
{
session.Open(sessionOp);
var list = session.ListDirectory(dir);
Console.WriteLine(list);
}
The error I get is, "Failed to Connect" from WinSCP
How can I access this FTPS?
What you did is configuring the HTTP Proxy port to 990. Instead you should configure the FTPS port.
SessionOptions sessionOp = new SessionOptions()
{
FtpSecure = FtpSecure.Implicit,
Protocol = Protocol.Ftp,
HostName = IP,
UserName = userName,
Password = password,
PortNumber = 990
};
and remove the lines
sessionOp.AddRawSettings("ProxyMethod", "3");
sessionOp.AddRawSettings("ProxyPort", "990");
Also, I suggest using the WinSCP GUI to try this instead of FileZilla, considering that the library is related to the GUI.

Files not getting transferred from Windows to Linux remote server

I am trying to use WinSCP in visual studio. I downloaded and installed WinSCP using the Managed NuGet package. I have used the below code in a web application to transfer one of the files to a remote Linux server. The code executes fine without any error, but the file is not transferred. I logged in using PuTTY to verify if the file has actually transferred, but could not locate the file. Below is the code used
public int Upload(String HostName, String UserName, String Password, String remotePath, String localFilePath)
{
int result = 0;
Session session = null;
try
{
// Setup session options
SessionOptions sessionOptions = new SessionOptions
{
Protocol = Protocol.Ftp,
HostName = HostName,
UserName = UserName,
Password = Password,
Timeout = TimeSpan.FromDays(1),
};
using (session = new Session())
{
// Connect
session.Open(sessionOptions);
// upload files
TransferOptions transferOptions = new TransferOptions();
transferOptions.TransferMode = TransferMode.Ascii;
TransferOperationResult transferResult = null;
transferResult = session.PutFiles(localFilePath, remotePath, false, transferOptions);
// Throw on any error
transferResult.Check();
// Print results
foreach (TransferEventArgs transfer in transferResult.Transfers)
{
Console.WriteLine("Upload of {0} succeeded", transfer.FileName);
}
session.GetFiles(#"\\remoteserver\folder1\folder_backups\test_files\test1.txt", #"d:\folder3\").Check();
}
result = 0;
}
catch (Exception e)
{
Console.WriteLine("Error: {0}", e);
result = 1;
}
finally
{
if (session != null)
{
session.Dispose();
}
}
return result;
}
The arguments are passed as below:
project1.Upload("remote host server", "username", "password", #"\\remote host server\folder1\folder_backups\test_files\", Fileupload1.PostedFile.FileName);
The code executes without any error, but no file is uploaded nor downloaded. How to fix this?
Thanks
After the login happens in GUI - it points to /home/UserId . But the folder which i want to move the files exist in /folder1
If remote path you want to use is /folder1/, use that for remotePath argument of your Upload method, instead of obviously wrong value #"\\remote host server\folder1\folder_backups\test_files\".
project1.Upload("host", "user", "password", "/folder1/", Fileupload1.PostedFile.FileName);
Not entirely sure but looks like you've set the protocol to FTP which may not be supported by the server. If you're able to login via putty then that means SSH connection is possible. Try setting the protocol to SFTP.

How to SFTP authenticate using password or SSH fingerprint WinSCP C# .NET assembly

I'm trying to connect to a server with a SFTP connection, but I'm trying to authenticate with SSH fingerprint, if this is not correct, then should attempt with the SFTP password.
The issue that I'm having is that need both of them to access to the server, that should be different, if is not the SSH fingerprint, then try with the password, but is not working.
There is a way to validate first the fingerprint and if is not correct, validate the user password?
This is what I have:
public string FilesSFTP_FTP()
{
TransferOptions TransferOption = new TransferOptions();
TransferOperationResult TransferResult;
SessionOptions sessionoptions = new SessionOptions();
Session session = new Session();
if (DataFile.sTransportType == "S")
{
sessionoptions.Protocol = Protocol.Sftp;
sessionoptions.PortNumber = 22;
sessionoptions.SshHostKeyFingerprint = DataFile.sFingerPrint;
}
else if (DataFile.sTransportType == "F")
{
sessionoptions.Protocol = Protocol.Ftp;
sessionoptions.PortNumber = 21;
}
sessionoptions.HostName = DataFile.sIPAddress;
sessionoptions.UserName = DataFile.sUserID;
sessionoptions.Password = DataFile.sPassword;
TransferOption.TransferMode = TransferMode.Binary;
TransferOption.PreserveTimestamp = false;
TransferOption.ResumeSupport.State = TransferResumeSupportState.Off;
session.Open(sessionoptions);
}
There is another property that it need to be set?
You cannot "authenticate with SSH fingerprint".
The SessionOptions.SshHostKeyFingerprint is to verify the server's host key. Not to authenticate the user.
To authenticate the user, you need to use the SessionOptions.SshPrivateKeyPath.
See Understanding SSH key pairs to learn the difference.
As for your question. You can set both the SessionOptions.SshPrivateKeyPath and the SessionOptions.Password. WinSCP will first try the private key, and only if that fails, it will fall back to the password. (Or it will use both, is the server requires that)

Categories