From 14fd7e28018dc7aa27157f237f2c617e684e5c1d Mon Sep 17 00:00:00 2001 From: Kyle Spearrin Date: Mon, 11 Mar 2019 23:31:45 -0400 Subject: [PATCH] throttle block messages and base64 encode them --- .../AzureQueueBlockIpService.cs | 17 ++++++++++++---- src/Core/Utilities/CoreHelpers.cs | 20 +++++++++++++++++++ 2 files changed, 33 insertions(+), 4 deletions(-) diff --git a/src/Core/Services/Implementations/AzureQueueBlockIpService.cs b/src/Core/Services/Implementations/AzureQueueBlockIpService.cs index 5331497d49..00574f39ae 100644 --- a/src/Core/Services/Implementations/AzureQueueBlockIpService.cs +++ b/src/Core/Services/Implementations/AzureQueueBlockIpService.cs @@ -2,6 +2,7 @@ using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Queue; using System; +using Bit.Core.Utilities; namespace Bit.Core.Services { @@ -10,6 +11,7 @@ namespace Bit.Core.Services private readonly CloudQueue _blockIpQueue; private readonly CloudQueue _unblockIpQueue; private bool _didInit = false; + private Tuple _lastBlock; public AzureQueueBlockIpService( GlobalSettings globalSettings) @@ -24,13 +26,20 @@ namespace Bit.Core.Services public async Task BlockIpAsync(string ipAddress, bool permanentBlock) { await InitAsync(); - var blockMessage = new CloudQueueMessage(ipAddress); - await _blockIpQueue.AddMessageAsync(blockMessage); + var now = DateTime.UtcNow; + if(_lastBlock != null && _lastBlock.Item1 == ipAddress && _lastBlock.Item2 == permanentBlock && + (now - _lastBlock.Item3) < TimeSpan.FromMinutes(1)) + { + // Already blocked this IP recently. + return; + } + _lastBlock = new Tuple(ipAddress, permanentBlock, now); + var message = new CloudQueueMessage(CoreHelpers.Base64UrlEncodeString(ipAddress)); + await _blockIpQueue.AddMessageAsync(message); if(!permanentBlock) { - var unblockMessage = new CloudQueueMessage(ipAddress); - await _unblockIpQueue.AddMessageAsync(unblockMessage, null, new TimeSpan(0, 15, 0), null, null); + await _unblockIpQueue.AddMessageAsync(message, null, new TimeSpan(0, 15, 0), null, null); } } diff --git a/src/Core/Utilities/CoreHelpers.cs b/src/Core/Utilities/CoreHelpers.cs index c390a2acf6..a1a59a6d27 100644 --- a/src/Core/Utilities/CoreHelpers.cs +++ b/src/Core/Utilities/CoreHelpers.cs @@ -317,6 +317,26 @@ namespace Bit.Core.Utilities !normalizedSetting.Equals("replace"); } + public static string Base64EncodeString(string input) + { + return Convert.ToBase64String(Encoding.UTF8.GetBytes(input)); + } + + public static string Base64DecodeString(string input) + { + return Encoding.UTF8.GetString(Convert.FromBase64String(input)); + } + + public static string Base64UrlEncodeString(string input) + { + return Base64UrlEncode(Encoding.UTF8.GetBytes(input)); + } + + public static string Base64UrlDecodeString(string input) + { + return Encoding.UTF8.GetString(Base64UrlDecode(input)); + } + public static string Base64UrlEncode(byte[] input) { var output = Convert.ToBase64String(input)