NullifyNetwork

The blog and home page of Simon Soanes
Skip to content
[ Log On ]

So I have encountered a situation where I need to use two factor authentication and recently bought a couple of Yubico YubiKey's to investigate them as a potential solution where I can't use smart cards (mostly with other users who can't install the appropriate drivers or on locked down systems/internet cafe's).

They are fairly cheap (particularly in bulk) and provide similar functionality to an RSA Securid but without the need to type the password (they act as a keyboard and type onto the computer, but can't be modified by the computer in question).  They also have two 'slots' for different tokens, you can touch the button once for one and touch and hold for a second one time key.

Whilst there's plenty of code examples around for them (the company are extremely open), I haven't found a simple, logical C# library/class I could use to do authentication locally (they supply ones for remote auth on their servers) - there were always multiple files and loads of code in peoples projects.

My intention is to write a Windows SubAuthentication DLL (in C++ but I learn in C#) to use with these keys which also still checks your normal password - so when remote desktop'ing, using something that authenticates to Windows or using the Windows Radius server (NPS) to authenticate VPN's you can choose to either supply your normal password, or if you're on a system you don't trust you can use your username/low security pin code and Yubikey.

So here's my take on the decoding of a Yubikey's input - note that I'm not interested in making a software token though so the class doesn't generate values for the random value (if you wanted to do this you just need to ask RNGCryptoProvider for a few bytes of random though) and there's also no incrementing of the sessions, in-session use counters or timestamps included - however I did include the code to encrypt it appropriately if you do supply all the values.

To use this class you just need to call it like so - where privateKey is a byte[] array with the private key in and otpCode is a string like "fkfthfffktbnreffrghcldrffeclcgkt" output from a touch of the Yubikey:-

YubiKey otp = YubiKey.FromModHex(privateKey, otpCode);
if (otp.UidMatch(checkIdentity))
{
Console.WriteLine("Decoded the YubiKey's OTP code:-");
Console.WriteLine("\tSession:\t" + otp.SessionCounter.ToString());
Console.WriteLine("\tCount in session:\t" + otp.SessionUseCount.ToString());
Console.WriteLine("\tTime (high):\t" + otp.TimestampHighPart.ToString());
Console.WriteLine("\tTime (low):\t" + otp.TimestampLowPart.ToString());
Console.WriteLine("\tTime (low):\t" + otp.Uid.ToString());
}
else
{
Console.WriteLine("Failed to identify the keys correct OTP");
}

 

And you can decode the private key/identity as they're displayed in the YubiKey personalisation tool with the following handy (but not super efficient) hex to byte algorithms:-

 

public static byte[] StringHexDecode(string hexData)
{
List<byte> data = new List<byte>();
foreach (string b in hexData.Split(' '))
{
data.Add(Convert.ToByte(b, 16));
}
return data.ToArray();
}

public static string StringHexEncode(byte[] hexData)
{
return BitConverter.ToString(hexData).Replace('-'' ');
}

And finally here's the actual Yubikey class including the algorithm to decrypt the data that the USB dongles actually output in 'ModHex' which is an odd keyboard language independent format but seems to work quite well:-

/// <summary>
/// A YubiKey OTP is symmetric two-factor auth key, this class allows decoding and validating them
/// </summary> public class YubiKey {
public YubiKey()
{
}

private const int CRC_OK_RESIDUE = 0xf0b8; /// <summary>
/// Unique (secret) ID.
/// </summary> public byte[] Uid = new byte[6]; /// <summary>
/// Session counter (incremented by 1 at each startup).  High bit
/// indicates whether caps-lock triggered the token.
/// </summary>
public UInt16 SessionCounter; /// <summary>
/// Timestamp incremented by approx 8Hz (low part).
/// </summary>
public UInt16 TimestampLowPart; /// <summary>
/// Timestamp (high part).
/// </summary>
public byte TimestampHighPart;
/// <summary>
/// Number of times used within session + activation flags.
/// </summary> public byte SessionUseCount; /// <summary>
/// Pseudo-random value.
/// </summary>
public UInt16 RandomValue; /// <summary>
/// CRC16 value of all fields.
/// </summary>
public UInt16 CRC;

/// <summary>
/// Does the included UID match the one we expected?
/// </summary>
/// <param name="uid"></param>
/// <returns></returns>
public bool UidMatch(byte[] uid)
{
for (int i = 0; i < uid.Length; i++)
{
if (Uid[i] != uid[i])
{
return false;
}
}
return true;
}

#region Post Decryption Conversion

private static int calculateCrc(byte[] b)
{
int crc = 0xffff;

for (int i = 0; i < b.Length; i += 1)
{
crc ^= b[i] & 0xFF;
for (int j = 0; j < 8; j++)
{
int n = crc & 1;
crc >>= 1;
if (n != 0)
{
crc ^= 0x8408;
}
}
}
return crc;
}

internal static YubiKey OtpFromRawByteArray(byte[] input)
{
if (input.Length < 16)
{
throw new YubiKeyException("Invalid OTP data - the amount supplied was
insufficient for a six byte identity."
);
}

if (calculateCrc(input) != CRC_OK_RESIDUE)
{
throw new YubiKeyException("CRC was invalid on that OTP");
}

YubiKey u = new YubiKey();
u.Uid = input.Take(6).ToArray();
u.SessionCounter = BitConverter.ToUInt16(input, 6);
u.TimestampLowPart = BitConverter.ToUInt16(input, 8);
u.TimestampHighPart = input[10];
u.SessionUseCount = input[11];
u.RandomValue = BitConverter.ToUInt16(input, 12);
u.CRC = BitConverter.ToUInt16(input, 14);
return u;
}

internal static byte[] RawByteArrayFromOtp(YubiKey input)
{
List<byte> data = new List<byte>();
data.AddRange(input.Uid);
data.AddRange(BitConverter.GetBytes(input.SessionCounter));
data.AddRange(BitConverter.GetBytes(input.TimestampLowPart));
data.Add(input.TimestampHighPart);
data.Add(input.SessionUseCount);
data.AddRange(BitConverter.GetBytes(input.RandomValue));
data.AddRange(BitConverter.GetBytes(input.CRC));
return data.ToArray();
}
#endregion

#region Cryptographic wrapper
internal byte[] AESEncrypt(byte[] data, byte[] key, byte[] iv)
{
Aes enc = Aes.Create();
enc.Key = key;
enc.IV = iv;
enc.Padding = PaddingMode.None;
using (ICryptoTransform transform = enc.CreateEncryptor())
{
byte[] output = transform.TransformFinalBlock(data, 0, data.Length);
return output;
}
}

internal static byte[] AESDecrypt(byte[] data, byte[] key, byte[] iv)
{
Aes aesImplementation = Aes.Create();
aesImplementation.Key = key;
aesImplementation.IV = iv;
aesImplementation.Padding = PaddingMode.None;

using (ICryptoTransform transform = aesImplementation.CreateDecryptor())
{
byte[] output = transform.TransformFinalBlock(data, 0, data.Length);

return output;
}
}
#endregion

#region ModHex Support

private const string alphabet = "cbdefghijklnrtuv";

internal static string ModHexEncode(byte[] data)
{
StringBuilder result = new StringBuilder();

for (int i = 0; i < data.Length; i++)
{
result.Append(alphabet[(data[i] >> 4) & 0xf]);
result.Append(alphabet[data[i] & 0xf]);
}

return result.ToString();
}

internal static byte[] ModHexDecode(String s)
{
List<byte> baos = new List<byte>();
int len = s.Length;

bool toggle = false;
int keep = 0;

for (int i = 0; i < len; i++)
{
char ch = s[i];
int n = alphabet.IndexOf(ch.ToString().ToLower());
if (n == -1)
{
throw new YubiKeyException(s + " is not properly encoded");
}

toggle = !toggle;

if (toggle)
{
keep = n;
}
else
{
baos.Add((byte)((keep << 4) | n));
}
}
return baos.ToArray();
}

#endregion

#region Factory helpers
/// <summary>
/// Create a Yubikey object from the mod hex and the private key
/// </summary>
/// <param name="privateKey">The private key to decrypt with</param>
/// <param name="modHex">The modhex content</param>
/// <returns>A yubikey object</returns>
public static YubiKey FromModHex(byte[] privateKey, string modHex)
{
//no IV in use
byte[] inputOTP = ModHexDecode(modHex);
byte[] decrypted = AESDecrypt(inputOTP, privateKey, new byte[16]);
return OtpFromRawByteArray(decrypted);
}

/// <summary>
/// Convert this yubikey instance into a mod-hex OTP string
/// </summary>
/// <param name="privateKey">The private key to encrypt with</param>
/// <returns>The modhext content</returns>
public string ToModHex(byte[] privateKey)
{
byte[] clearotp = RawByteArrayFromOtp(this);
byte[] encrypted = AESEncrypt(clearotp, privateKey, new byte[16]);
return ModHexEncode(encrypted);
}
#endregion

public class YubiKeyException : Exception
{
public YubiKeyException(string message) : base(message)
{

}
} }

Once decrypted it is a simple matter to verify it is a key with a particular code (the simple act of decryption should do that but there's a UID included inside too) and that the Session counter and SessionUseCount have been incremented appropriately to prevent re-use of existing keys.

Note that if you are trying to decode a key which has a prefix added you are interested in the last 32 characters of the output - the first few characters by default on a key are a static identifier so that it's possible to identify which encryption key to use to decrypt the token; I've turned this off and favour the user having to enter their own username/password prior to using the key.

Permalink