Browse Source

improve bot token validation by trying to decode user id from token

Try to decode the user id from the supplied bot token as a way of validating the token. If this should fail, indicate that the token is invalid.
pull/1206/head
Chris Johnston 6 years ago
parent
commit
f23f781a90
1 changed files with 42 additions and 0 deletions
  1. +42
    -0
      src/Discord.Net.Core/Utils/TokenUtils.cs

+ 42
- 0
src/Discord.Net.Core/Utils/TokenUtils.cs View File

@@ -16,6 +16,45 @@ namespace Discord
/// </remarks> /// </remarks>
internal const int MinBotTokenLength = 58; internal const int MinBotTokenLength = 58;


/// <summary>
/// Checks the validity of a bot token by attempting to decode a ulong userid
/// from the bot token.
/// </summary>
/// <param name="message">
/// The bot token to validate.
/// </param>
/// <returns>
/// True if the bot token was valid, false if it was not.
/// </returns>
internal static bool CheckBotTokenValidity(string message)
{
// split each component of the JWT
var segments = message.Split('.');

// ensure that there are three parts
if (segments.Length != 3)
return false;

try
{
// decode the first segment as base64
var v = Convert.FromBase64String(segments[0]);
BitConverter.ToUInt64(v, 0);
// if no exception thrown, token is valid
return true;
}
catch (FormatException)
{
// ignore exception, if contains invalid base64 characters return false
return false;
}
catch (ArgumentException)
{
// ignore exceptions thrown by BitConverter
return false;
}
}

/// <summary> /// <summary>
/// Checks the validity of the supplied token of a specific type. /// Checks the validity of the supplied token of a specific type.
/// </summary> /// </summary>
@@ -43,6 +82,9 @@ namespace Discord
// pre-existing tokens // pre-existing tokens
if (token.Length < MinBotTokenLength) if (token.Length < MinBotTokenLength)
throw new ArgumentException(message: $"A Bot token must be at least {MinBotTokenLength} characters in length.", paramName: nameof(token)); throw new ArgumentException(message: $"A Bot token must be at least {MinBotTokenLength} characters in length.", paramName: nameof(token));
// check the validity of the bot token by decoding the ulong userid from the jwt
if (!CheckBotTokenValidity(token))
throw new ArgumentException(message: "The Bot token was invalid.", paramName: nameof(token));
break; break;
default: default:
// All unrecognized TokenTypes (including User tokens) are considered to be invalid. // All unrecognized TokenTypes (including User tokens) are considered to be invalid.


Loading…
Cancel
Save