Last active
September 25, 2016 08:03
-
-
Save troyhunt/d6bca97ac4a79bd3109f888bb0515281 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Configuration; | |
public static void Run(TimerInfo myTimer, TraceWriter log) | |
{ | |
log.Info($"C# Timer trigger function executed at: {DateTime.Now}"); | |
RemoveIpBlocks(log).Wait(); | |
} | |
static async Task RemoveIpBlocks(TraceWriter log) | |
{ | |
var zoneId = ConfigurationManager.AppSettings["ZoneId"]; | |
var xAuthEmail = ConfigurationManager.AppSettings["X-Auth-Email"]; | |
var xAuthKey = ConfigurationManager.AppSettings["X-Auth-Key"]; | |
var path = $"/client/v4/zones/{zoneId}/firewall/access_rules/rules?per_page=100"; | |
using (var client = new HttpClient()) | |
{ | |
client.BaseAddress = new Uri("https://api.cloudflare.com"); | |
client.DefaultRequestHeaders.Accept.Clear(); | |
client.DefaultRequestHeaders.Add("X-Auth-Email", xAuthEmail); | |
client.DefaultRequestHeaders.Add("X-Auth-Key", xAuthKey); | |
var response = await client.GetAsync(path); | |
if (response.IsSuccessStatusCode) | |
{ | |
var firewallRules = await response.Content.ReadAsAsync<dynamic>(); | |
foreach (var firewallRule in firewallRules.result) | |
{ | |
var notes = firewallRule.notes.ToString(); | |
if (notes.StartsWith("rate-limit-abuse-")) | |
{ | |
var dateString = notes.Replace("rate-limit-abuse-", string.Empty); | |
var ruleCreated = DateTime.Parse(dateString); | |
var ruleDescription = $"IP {firewallRule.configuration.value} added on {ruleCreated.ToString("s")} -"; | |
// Delete rules that were created more than a day ago | |
if (ruleCreated < DateTime.UtcNow.AddDays(-1)) | |
{ | |
path = $"/client/v4/zones/{zoneId}/firewall/access_rules/rules/{firewallRule.id}"; | |
await client.DeleteAsync(path); | |
log.Info($"{ruleDescription} deleted"); | |
} | |
else | |
{ | |
log.Info($"{ruleDescription} not old enough"); | |
} | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment