How do I see the password of the current user, c# - c#

I am developing a program in C# and I am having a problem with Windows credentials.
I need the program return me the user name and password.
using (WebClient client = new WebClient())
{
string[] user = Convert.ToString(WindowsIdentity.GetCurrent().Name).Split('\\');
string userName = user[1];
label1.Text = userName.ToString();
label2.Text = passwd.ToString();
//client.Credentials = new NetworkCredential(userName, "1234"); //1234 = password
//client.DownloadFile("http://**intranet**/servicosuporte/Documentos%20Partilhados/assistente_remoto.zip", #"C:\assistremoto.zip");
}

You are unable to access a user's password in this way. Passwords are not reversible, and are hashed. This is a one-way operation.
If you want to use the user's existing credentials, you can use:
System.Net.CredentialCache.DefaultNetworkCredentials //for network
and
System.Net.CredentialCache.DefaultCredentials //for local

Related

Active Directory The object already exists using SetPassword and new object []{}

I'm hoping someone can explain this to me because I am at my wits end trying to resolve an issue I am having.
The error I am receiving is, "The object already exists." whenever I am trying to run our ResetPassword function. The weird thing is I ONLY receive this error if the user account has had their password reset before. If I either create a new account with a new password, or search for a user in the database that has not had the ResetPassword function called on their account, then it will let me call this function once. Note: On this one time it lets me run the function the password does get reset. Any account that has already run ResetPassword will prompt the object already exists error.
public static void ResetPassword(DirectoryEntry User, string password)
{
User.Invoke("SetPassword", new object[] { password });
User.Properties["LockOutTime"].Value = 0x0000; //unlock account
int val = (int)User.Properties["userAccountControl"].Value;
User.Properties["userAccountControl"].Value = val & ~0x2; //Enable account
User.CommitChanges();
Logs.CreateLogEntry("Reset password", User);
User.Close();
}
As you can see, we are passing in a DirectoryEntry user, along with a generated new password. We are using an anonymous login on the backend of our IIS website to have admin credentials high enough to use SetPassword.
You need to provide credentials of a user in AD that has admin privileges to reset passwords.
public static void ResetPassword(string username, string password)
{
string adminUser = "YourAdminUserIdInAD";
string adminPass = "YourAdminUserPasswordInAD";
string ldapString = "LDAP://YourLDAPString";
DirectoryEntry dEntry = new DirectoryEntry(ldapString , adminUser, adminPass, AuthenticationTypes.Secure);
DirectorySearcher deSearch = new DirectorySearcher(dEntry) {
SearchRoot = dEntry,
Filter = "(&(objectCategory=user)(cn=" + username + "))"
};
var directoryEntry = deSearch.FindOne();
directoryEntry.Invoke("SetPassword", new object[] { password });
directoryEntry.Properties["LockOutTime"].Value = 0x0000; //unlock account
int val = (int)directoryEntry.Properties["userAccountControl"].Value;
directoryEntry.Properties["userAccountControl"].Value = val & ~0x2;
directoryEntry.CommitChanges();
Logs.CreateLogEntry("Reset password", User);
directoryEntry.Close();
}

Connect to eDirectory using application credentials. Then authenticate user

I need to connect to NetIQ eDirectory using .NET & C#. The connection must be opened using application credentials. Once the connection is opened, I need to validate user credentials under the authority of the application credentials using a similar method as S.DS.AccountManagement.
using (var context = new PrincipalContext(ContextType.Domain, path, appUserDn, appPassword))
{
//Username and password for authentication.
var valid = context.ValidateCredentials(userDn, password);
}
I tried Novell.Directory.Ldap, S.DS.DirectoryEntry, & S.DS.AccountManagement. The last one requires AD and does not apply.
Test using Novell.Directory.Ldap..
using (var cn = new LdapConnection())
{
cn.Connect(server, int.Parse(port));
cn.Bind(appUserDn, appPassword); //throws exception if invalid credentials..
var passwordAttr = new LdapAttribute("userPassword", password);
cn.Compare(userDn, passwordAttr); // Only compares password, so no locked account check, etc.
}
My current prototype uses S.DS.Protocols.
var networkCredential = new NetworkCredential(
appUserDn,
appPassword);
using (proto.LdapConnection cn = new proto.LdapConnection(new proto.LdapDirectoryIdentifier(server, int.Parse(port)), networkCredential, proto.AuthType.Basic))
{
cn.Bind();
/// Next validate user credentials..
}
I cannot find a way to validate user credentials other than reassigning NetworkCrentials and rebinding using the individual's username & password. How should I proceed?
It turns out our client got it wrong. The correct way is to bind the connection directly to an individual's credentials as I demonstrate in the Novell.Directory.Ldap example.
There was a posting on NetIQ's forum about executing a shell script but I did not get it working.

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)

Setting up LDAP Connection - LDAPError Invalid Credentials

I am trying to connect to via LDAP for the first time. I am just trying to simply check if a user can login. After trying to connect I am getting an invalid credentials error 49 and error code 81 server is unavailable. I am passing the right user credentials so this should be validating and I am able to connect via JXplorer.
In JXplorer I have my host as ldap.my.edu port as 389
User dn as: Uid=myuser,OU=People, DC=ua,DC=edu
then mypass.
I believe I am not properly translating this to LdapConnection and the network credential. This is my first time so any help would be very appreciated.
const string server = "ldap.my.edu:389/OU=People,DC=my,DC=edu";
const string domain = "ldap.my.edu";
string password = "mypass";
string userName = "myuser";
try
{
using (var ldapConnection = new LdapConnection(server))
{
var networkCredential = new NetworkCredential(userName, password, domain);
ldapConnection.SessionOptions.SecureSocketLayer = true;
ldapConnection.AuthType = AuthType.Negotiate;
ldapConnection.Bind(networkCredential);
}
If you don't have SSL (LDAPS) enabled on this server, which looks to be the case, then you'll want to make sure you set :
ldapConnection.SessionOptions.SecureSocketLayer = false
Or, you can just not set it at all - LdapConnection will default to unsecured port 389 (LDAP) by default, if this isn't explicitly set.
An example, using the values you provided in your question, would be something like this (note that I'm applying the domain to the NetworkCredential and not the LdapConnection class itself) :
// the username and password to authenticate
const string domain = "OU=People,DC=my,DC=edu";
string password = "mypass";
string userName = "myuser";
// define your connection
LdapConnection ldapConnection = new LdapConnection("ldap.my.edu:389");
try
{
// authenticate the username and password
using (ldapConnection)
{
// pass in the network creds, and the domain.
var networkCredential = new NetworkCredential(username, password, domain);
// if we're using unsecured port 389, set to false. If using port 636, set this to true.
ldapConnection.SessionOptions.SecureSocketLayer = false;
// since this is an internal application, just accept the certificate either way
ldapConnection.SessionOptions.VerifyServerCertificate += delegate { return true; };
// to force NTLM\Kerberos use AuthType.Negotiate, for non-TLS and unsecured, just use AuthType.Basic
ldapConnection.AuthType = AuthType.Basic;
// authenticate the user
ldapConnection.Bind(networkCredential);
}
catch (LdapException ldapException)
{
//Authentication failed, exception will dictate why
}
}
Try port 3268 for Global Catalog

Searching through Active Directory in C# and authenticate with current User

What i want to do:
A user is logged into my application with his user credentials. A form has as input only a pNumber, the application should search through active directory to find the user with that number and fill out different input fields automatically (in this example only name and email).
What i already have (C# Code, .Net 4.0):
public static string[] getUser(string pNumber) {
string[] user = new string[4];
NetworkCredential credential = CredentialCache.DefaultNetworkCredentials;
string userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
string DomainPath = "LDAP://DC=****,DC=com";
string strAccountId = userName;
string strPassword = "******";
DirectoryEntry adsEntry = new DirectoryEntry(DomainPath, strAccountId, strPassword);
DirectorySearcher adsSearcher = new DirectorySearcher(adsEntry);
adsSearcher.Filter = "(pNumber=" + pNumber + ")";
SearchResult adsSearchResult = adsSearcher.FindOne();
if (adsSearchResult != null) {
user[0] = adsSearchResult.Properties["sAMAccountName"][0].ToString();
user[1] = adsSearchResult.Properties["mail"][0].ToString();
}
return user;
}
If i put in values for strAccountId and strPassword i know have access to AD this works fine. But this is only a workaround. I would like to authenticate to AD with the current users credentials. I can get the current username, but i think it is not possible to get the password. So i looked into other posibilitys to authenticate with DirectoryEntry here. (What i didnt really get was the DirectoryEntry(Object) Constructor)
My Question:
Are there alternatives i can search through AD with C# with the current user credentials?
DirectorySearcher ds = new DirectorySearcher(de);
if the current user has access it will be good if not you get an exception.

Categories