diff options
| author | 2020-05-14 10:34:37 -0700 | |
|---|---|---|
| committer | 2020-05-14 10:39:54 -0700 | |
| commit | 73bcb2b434a30761494bbedd914508964c6fbbad (patch) | |
| tree | d2575ded6078d417c5779d2fe62217f206951a46 | |
| parent | Token remover: add logs to clarify why token is invalid (diff) | |
Token remover: fix timestamp check
The timestamp calculation was incorrect. The bytes need to be
interpreted as big-endian and the result is just a timestamp rather than
a snowflake.
Diffstat (limited to '')
| -rw-r--r-- | bot/cogs/token_remover.py | 26 | 
1 files changed, 16 insertions, 10 deletions
diff --git a/bot/cogs/token_remover.py b/bot/cogs/token_remover.py index 244d52edb..957c8a690 100644 --- a/bot/cogs/token_remover.py +++ b/bot/cogs/token_remover.py @@ -2,13 +2,10 @@ import base64  import binascii  import logging  import re -import struct  import typing as t -from datetime import datetime  from discord import Colour, Message  from discord.ext.commands import Cog -from discord.utils import snowflake_time  from bot.bot import Bot  from bot.cogs.moderation import ModLog @@ -29,7 +26,7 @@ DELETION_MESSAGE_TEMPLATE = (      "Feel free to re-post it with the token removed. "      "If you believe this was a mistake, please let us know!"  ) -DISCORD_EPOCH_TIMESTAMP = datetime(2017, 1, 1) +DISCORD_EPOCH = 1_420_070_400_000  TOKEN_EPOCH = 1_293_840_000  TOKEN_RE = re.compile(      r"[^\s\.()\"']+"  # Matches token part 1: The user ID string, encoded as base64 @@ -160,18 +157,27 @@ class TokenRemover(Cog):      @staticmethod      def is_valid_timestamp(b64_content: str) -> bool:          """ -        Check potential token to see if it contains a valid timestamp. +        Return True if `b64_content` decodes to a valid timestamp. -        See: https://discordapp.com/developers/docs/reference#snowflakes +        If the timestamp is greater than the Discord epoch, it's probably valid. +        See: https://i.imgur.com/7WdehGn.png          """          b64_content += '=' * (-len(b64_content) % 4)          try: -            content = base64.urlsafe_b64decode(b64_content) -            snowflake = struct.unpack('i', content)[0] -        except (binascii.Error, struct.error, ValueError): +            decoded_bytes = base64.urlsafe_b64decode(b64_content) +            timestamp = int.from_bytes(decoded_bytes, byteorder="big") +        except (binascii.Error, ValueError) as e: +            log.debug(f"Failed to decode token timestamp '{b64_content}': {e}") +            return False + +        # Seems like newer tokens don't need the epoch added, but add anyway since an upper bound +        # is not checked. +        if timestamp + TOKEN_EPOCH >= DISCORD_EPOCH: +            return True +        else: +            log.debug(f"Invalid token timestamp '{b64_content}': smaller than Discord epoch")              return False -        return snowflake_time(snowflake + TOKEN_EPOCH) < DISCORD_EPOCH_TIMESTAMP  def setup(bot: Bot) -> None:  |