I was trying to connect to SFTP through code to upload some data. As it has two factor authentication, I need to do some authentication with the Yubikey device before connecting to SFTP. I have written the code to authenticate but I am getting exceptions while authenticating the yubikey device. Is there anything I am doing wrong? Can someone please suggest if there's any better way to do it.
Initially, I was getting error of yubikey pin is more than 8 characters. I have trimmed and captured the first 8 characters to authenticate. Initially, yubikey authentication was successful but was failing in connecting to SFTP and was giving me exception, 'No suitable authentication method found to complete authentication (keyboard-interactive).'" .
But after few attempts, even the yubikey authentication code was failing and giving the exception "There are no retries remaining for a PIN, PUK, or other authentication element".
What I have tried:
try
{
YubiKeyDevice yubiKeyDevice =
(YubiKeyDevice)YubiKeyDevice.FindAll().FirstOrDefault();
if (yubiKeyDevice == null)
{
return;
}
using (var pivSession = new PivSession(yubiKeyDevice))
{
yubiKeyPin = yubiKeyPin.Substring
(0, Math.Min(yubiKeyPin.Length, 8));
byte[] pinBytes = Encoding.UTF8.GetBytes(yubiKeyPin);
bool result = pivSession.TryVerifyPin
(pinBytes, out retriesRemaining);
if (result)
{
using (var client = new SftpClient
(host, port, username, password))
{
try
{
client.Connect();
if (client.IsConnected)
{
using (var fileStream =
new FileStream(sourcefile, FileMode.Open))
{
client.UploadFile
(fileStream, destinationpath +
System.IO.Path.GetFileName
(sourcefile));
}
}
}
finally
{
client.Disconnect();
}
}
}
}
}