Auth fail error when using SharpSSH - c#

I am trying to connect to a Solaris/Unix server using a C# class to read system information/configuration, memory usage etc.
My requirement is to run the commands on the server from a C# application (as we do with a PuTTY client) and store the response in a string variable for later processing.
After some research, I found out that SharpSSH library can be used to do the same.
When I try to run my code, the following line gives me an Auth Fail exception.
I am confident that the credentials (server name, user name and password) are correct since I am able to log-in from the PuTTY client with the same credentials.
SshStream ssh = new SshStream(servername, username, password);
What am I doing wrong?
The following is the stack trace if it helps!
at Tamir.SharpSsh.jsch.Session.connect(Int32 connectTimeout)
at Tamir.SharpSsh.jsch.Session.connect()
at Tamir.SharpSsh.SshStream..ctor(String host, String username, String password)

After some research, I found a VB code which pointed me to the right direction. It seems that adding an additional event handler for the KeyboardInteractiveAuthenticationMethod helped to solve this. Hope this helps someone else.
void HandleKeyEvent(Object sender, AuthenticationPromptEventArgs e)
{
foreach (AuthenticationPrompt prompt in e.Prompts)
{
if (prompt.Request.IndexOf("Password:", StringComparison.InvariantCultureIgnoreCase) != -1)
{
prompt.Response = password;
}
}
}
private bool connectToServer()
{
try
{
KeyboardInteractiveAuthenticationMethod kauth = new KeyboardInteractiveAuthenticationMethod(username);
PasswordAuthenticationMethod pauth = new PasswordAuthenticationMethod(username, password);
kauth.AuthenticationPrompt += new EventHandler<AuthenticationPromptEventArgs>(HandleKeyEvent);
ConnectionInfo connectionInfo = new ConnectionInfo(serverName, port, username, pauth, kauth);
sshClient = new SshClient(connectionInfo);
sshClient.Connect();
return true;
}
catch (Exception ex)
{
if (null != sshClient && sshClient.IsConnected)
{
sshClient.Disconnect();
}
throw ex;
}
}

Related

FTP Connection issue- using FluentFTP for port 990 -TLS

I am trying download file through FTPS connection with port 990 (TLS) using FluentFTP.
But the code is not able to establish connection and showing exception as "The remote certificate is invalid according to the validation procedure."
The FTP server is connecting properly when I use FileZilla FTP tool manually (showing as it is connected through ftps over TLS (Implicit)
FtpClient fclient = new FtpClient(hostname, username, password);
fclient.EncryptionMode = FtpEncryptionMode.Implicit;
fclient.SslProtocols = SslProtocols.Tls12; //Also tried with TLS1 and TLS
fclient.Port = 990;
fclient.Connect();
Try this (taken from ConnectFTPSCertificate.cs example of FluentFTP). The important part is the callback OnValidateCertificate.
public static async Task ConnectFTPSCertificateAsync() {
var token = new CancellationToken();
using (var conn = new FtpClient("127.0.0.1", "ftptest", "ftptest")) {
conn.EncryptionMode = FtpEncryptionMode.Explicit;
conn.ValidateCertificate += new FtpSslValidation(OnValidateCertificate);
await conn.ConnectAsync(token);
}
}
private static void OnValidateCertificate(FtpClient control, FtpSslValidationEventArgs e) {
if (e.PolicyErrors == System.Net.Security.SslPolicyErrors.None) {
e.Accept = true;
}
else {
// add logic to test if certificate is valid here
// lookup the "Certificate" and "Chain" properties
e.Accept = false;
}
}
I experienced the same issue.
Pay attention that fluentFTP supports only external interfaces and not implicit
I also tried ftpWebRequest without success.
Try using winSCP.

How to read mail content through c# console application

MailRepository rep = new MailRepository("imap.mail.yahoo.com", 993, true, #"xxxxx#yahoo.com", "*******");
foreach (Message email in rep.GetUnreadMails("Inbox"))
{
//Console.WriteLine(string.Format("<p>{0}: {1}</p><p>{2}</p>", email.From, email.Subject, email.BodyHtml.Text));
Console.WriteLine(email.From);
Console.WriteLine(email.Subject);
Console.WriteLine(email.BodyHtml.Text);
if (email.Attachments.Count > 0)
{
foreach (MimePart attachment in email.Attachments)
{
Console.WriteLine(string.Format("<p>Attachment: {0} {1}</p>", attachment.ContentName, attachment.ContentType.MimeType));
}
}
}
Above is my code, which is used to read mail content. It's working fine when i tryed for gmail port, but while going for yahoo or some other. It's not allowing me to read the mail throwing exception. Is there any other source . Please guide me
First, check your credentials are correct.
Second, put a try catch in the constructor to see if you can get more info about the unhandled exception:
public MailRepository(string mailServer, int port, bool ssl, string login, string password)
{
try {
if (ssl) {
Client.ConnectSsl(mailServer, port);
}
else {
Client.Connect(mailServer, port);
}
Client.Login(login, password);
}
catch(Exception ex)
{
//Check the exception details here
}
}
Third, the origin of the MailRepository class appears to be from here that uses the Imap4Client implementation which others have complained doesn't work with Yahoo:
Connecting to yahoo email with IMAP4 MailSystem.NET
The accepted answer recommends using ImapX 2 - crossplatform IMAP library for .NET to handle GMail, Yahoo, etc.

C# script to connect to Oracle Directory Server Enterprise Edition

I have a C# script I am trying to use to connect to an Oracle Directory Server Enterprise Edition
So far i have had very little success.
I am receiving a Unknown error (0x80005000) error message
Can somebody tell me what I am doing wrong. I have been researching the web and most online boards say that this error message is because the LDAP in the path needs to be in uppercase letters.
As you can see I have done that but still no luck.
Below is my code
private static readonly string PATH = "LDAP://LDAPDEV.example.com:389/o=example.com";
private static readonly string USERNAME = uid=SERVICE_USR,ou=ApplicationIDs,o=example.com";
private static readonly string PASSWORD = "test1234";
string DN = "";
// connect to determine proper distinguishedname
DirectoryEntry Entry = new DirectoryEntry(Path, USERNAME, PASSWORD, AuthenticationTypes.None);
try
{
// Bind to the native AdsObject to force authentication.
Object obj = Entry.NativeObject;
DirectorySearcher Search = new DirectorySearcher(Entry);
Search.ReferralChasing = ReferralChasingOption.All
}
catch (Exception ex)
{
throw new Exception("Error looking up distinguishedname. ", ex);
}
finally
{
anonymousEntry.Close();
}
return DN;
}
string sDomain="LDAPDEV.example.com:389";
string sDefaultOU = #"o=example.com";
string sServiceUser = #"uid=user,ou=ApplicationIDs,o=example.com";
string sServicePassword = "password";
try
{
PrincipalContext oPrincipalContext = new PrincipalContext(ContextType.Domain, sDomain, sDefaultOU, ontextOptions.SimpleBind, sServiceUser,sServicePassword);
}
catch (Exception ex)
{
ex.Message;
}
Here is something that you can use to get some information by using PrincipalContext look at this working example and replace the values with your domain name values.
// if you are doing this via web application if not you can replace
// the Request/ServerVariables["LOGON_USER"]
// with Environment.UserName; this will return your user name like msmith for example so var userName = Environvironment.UserName;
var userName = Request.ServerVariables["LOGON_USER"].Split(new string[] {"\\"}, StringSplitOptions.RemoveEmptyEntries);
var pc = new PrincipalContext(ContextType.Domain,"yourdomain.com",null, null);
var userFind = UserPrincipal.FindByIdentity(pc, IdentityType.SamAccountName, userName);
this is basically all you need to see the information like email address SamAccountName ect.. use the debugger to inspect all the property values available in the pc variable and userFind variable

How to resolve a 'Bad packet length' error in SSH.NET?

I'm trying to upload files via SFTP, using SSH.NET. SFTPClient.Connect() throws an SshConnectionException with the message, "Bad packet length 1302334341." This is my code:
static void Main()
{
try
{
SftpClient sftp = new SftpClient(server, 22, userID, password);
sftp.Connect();
}
catch(Exception e)
{
Console.WriteLine(e.Message);
}
}
I saw in another discussion that this probably has to do with encryption. I'm using AES, and I have a host key. I don't understand how to enter the encryption, though. Based on that discussion, I was playing with this:
ConnectionInfo connectionInfo = new PasswordConnectionInfo(server, 22, userID, password);
connectionInfo.Encryptions.Clear();
connectionInfo.Encryptions.Add("aes","ssh-rsa 2048 11:22:34:d4:56:d6:78:90:01:22:6b:46:34:54:55:8a")
I know that's not the right set of arguments to pass to Encryptions.Add(), but I'm a little lost with using this library; can you help me figure out how to set the encryption properly (assuming that's the problem)?
Solved, in this discussion. I needed to remove encryptions using
foreach (var d in connectionInfo.Encryptions.Where(p => p.Key != "aes128-cbc").ToList())
{
connectionInfo.Encryptions.Remove(d.Key);
}
substituting in whichever encryption I intend to use

Create Windows User programmatically c# .net (using PricinpalUser / CreateProfile)

In a nutshell, what I'm trying to do is create a new user, which has the ability to log in.
I have plucked code from various sources, and tried to simplify it. However, I'm hitting a few stumbling blocks.
When I call UserPrincipal.Save() - it gives me an error
'The directory property cannot be found in the cache' with an
exception type of.. 'COMExceptioncrossed a native/managed boundary'.
For some reason, when I run my program directly (not through vs2010) it works fine. So I can get around that !
My main problem though, is that even though everything seems ok, when I try to log in, it comes up with the message 'loading desktop' or whatever it is, and then just says 'logging out'. So it's almost as if the profile hasn't been set up correctly.
The return value from the API 'CreateProfile' isn't 0, so maybe that's causing a problem.
Is there anything else I need to do ?
My Code is...
private void Run(string un, string pw)
{
UserPrincipal NewUP = CreateUser(un, pw);
AddGroup(NewUP, "Users");
AddGroup(NewUP, "HomeUsers");
CreateProfile(NewUP);
}
private UserPrincipal CreateUser(string Username, string Password)
{
PrincipalContext pc = new PrincipalContext(ContextType.Machine, Environment.MachineName);
UserPrincipal up = UserPrincipal.FindByIdentity(pc, IdentityType.SamAccountName, Username);
if (up == null)
{
up = new UserPrincipal(pc, Username, Password, true);
up.UserCannotChangePassword = false;
up.PasswordNeverExpires = false;
up.Save(); // this is where it crashes when I run through the debugger
}
return up;
}
private void AddGroup(UserPrincipal Up, string GroupName)
{
PrincipalContext pc = new PrincipalContext(ContextType.Machine, Environment.MachineName);
GroupPrincipal gp = GroupPrincipal.FindByIdentity(pc, GroupName);
if (!gp.Members.Contains(Up))
{
gp.Members.Add(Up);
gp.Save();
}
gp.Dispose();
}
private void CreateProfile(UserPrincipal Up)
{
int MaxPath = 240;
StringBuilder pathBuf = new StringBuilder(MaxPath);
uint pathLen = (uint)pathBuf.Capacity;
int Res = CreateProfile(Up.Sid.ToString(), Up.SamAccountName, pathBuf, pathLen);
}
Strangely, when this is run on a server machine (i.e. not my development machine) it works fine. I've got a feeling this is something to do with Windows 7, or my particular installation of it.
Thanks for your suggestions anyway.

Categories