From f23f781a9013b606032e554e3bd8568c39bc597c Mon Sep 17 00:00:00 2001 From: Chris Johnston Date: Fri, 30 Nov 2018 15:57:00 -0800 Subject: [PATCH] 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. --- src/Discord.Net.Core/Utils/TokenUtils.cs | 42 ++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/src/Discord.Net.Core/Utils/TokenUtils.cs b/src/Discord.Net.Core/Utils/TokenUtils.cs index 8fa846267..b0d1873ba 100644 --- a/src/Discord.Net.Core/Utils/TokenUtils.cs +++ b/src/Discord.Net.Core/Utils/TokenUtils.cs @@ -16,6 +16,45 @@ namespace Discord /// internal const int MinBotTokenLength = 58; + /// + /// Checks the validity of a bot token by attempting to decode a ulong userid + /// from the bot token. + /// + /// + /// The bot token to validate. + /// + /// + /// True if the bot token was valid, false if it was not. + /// + 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; + } + } + /// /// Checks the validity of the supplied token of a specific type. /// @@ -43,6 +82,9 @@ namespace Discord // pre-existing tokens if (token.Length < MinBotTokenLength) 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; default: // All unrecognized TokenTypes (including User tokens) are considered to be invalid.