Custom Rules WAF Update API

HELLO EVERYONE: I want to write a code that updates a firewall rule using Cloudflare Api.

THE PROCESS I WANT TO DO: want to write a code that I can remotely add a country to a rule that applies managed challange action to some countries with the “or” command.

NOTE: When adding countries to the rule, I want it to protect the countries that are already in the rule.

<?php

// API kimlik bilgilerinizi ve değiştirmek istediğiniz kuralın kimliğini girin
$auth_email = "EMAIL";
$auth_key = "APIKEY";
$zone_id = "ZONEID";
$rule_id = "RULEID";

// Eklenecek ülkeleri dizi olarak belirleyin
$new_countries = array("TR", "FR", "DE");

// API isteğinde kullanılacak URL'yi oluşturun
$url = "https://api.cloudflare.com/client/v4/zones/" . $zone_id . "/firewall/rules/" . $rule_id;

// API isteğinde kullanılacak güncelleme verisini belirleyin
$update_data = array(
  "action" => "challenge",
  "filter" => array(
    "id" => $rule_id,
    "expression" => build_expression($new_countries),
    "paused" => false
  ),
  "paused" => false
);

// API isteği için başlık bilgilerini belirleyin
$headers = array(
  "Content-Type: application/json",
  "X-Auth-Email: " . $auth_email,
  "X-Auth-Key: " . $auth_key
);

// cURL işlemini yapılandırın
$curl = curl_init();
curl_setopt_array($curl, array(
  CURLOPT_URL => $url,
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_CUSTOMREQUEST => "PUT",
  CURLOPT_POSTFIELDS => json_encode($update_data),
  CURLOPT_HTTPHEADER => $headers
));

// cURL isteğini çalıştırın
$response = curl_exec($curl);
$error = curl_error($curl);

// cURL işlemini kapatın
curl_close($curl);

// Yanıtta hatalar varsa, ekrana yazdırın
if ($error) {
  echo "cURL error: " . $error;
} else {
  echo $response;
}

// Belirli ülkeleri içeren bir Firewall Rule ifadesi oluşturun
function build_expression($countries) {
  $conditions = array();
  foreach ($countries as $country) {
    $conditions[] = "(ip.geoip.country eq \"" . $country . "\")";
  }
  return implode(" or ", $conditions);
}

Hello, I fixed the problem in the topic I opened and I want to share it with

Workers Code:

// Set the filter ID and new country
const filter_id = "FİLTERID";
const new_country = "CA";

// Set the API credentials and zone ID
const auth_email = "[email protected]";
const auth_key = "KEY";
const zone_id = "ZID";

// Get the filter details
addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request))
})

async function handleRequest(request) {
  try {
    const response = await fetch(`https://api.cloudflare.com/client/v4/zones/${zone_id}/filters/${filter_id}`, {
      headers: {
        "Content-Type": "application/json",
        "X-Auth-Email": auth_email,
        "X-Auth-Key": auth_key
      }
    });
    const filter = await response.json();

    console.log("Filter ID: " + filter.result.id);
    console.log("Filter Description: " + filter.result.description);
    console.log("Filter Expression: " + filter.result.expression);
    console.log("Filter Paused: " + (filter.result.paused ? "true" : "false"));
    console.log("Filter Ref: " + filter.result.ref);

    // Check if the new country is already in the filter expression
    const existing_countries = filter.result.expression.match(/ip\.geoip\.country eq "([A-Z]{2})"/g);
    if (existing_countries && existing_countries.includes(`ip.geoip.country eq "${new_country}"`)) {
      console.log("Bu ülke daha önce eklenmiş");
      return new Response("Bu ülke daha önce eklenmiş");
    }

    // Update the filter expression
    const expression = filter.result.expression + ` or (ip.geoip.country eq "${new_country}")`;
    const data = {
      expression: expression
    };
    const data_json = JSON.stringify(data);

    const response2 = await fetch(`https://api.cloudflare.com/client/v4/zones/${zone_id}/filters/${filter_id}`, {
      headers: {
        "Content-Type": "application/json",
        "X-Auth-Email": auth_email,
        "X-Auth-Key": auth_key
      },
      method: "PUT",
      body: data_json
    });
    const result = await response2.json();

    console.log("Ülke başarıyla eklendi!");
    return new Response("Ülke başarıyla eklendi!");
  } catch (error) {
    console.log(error);
    return new Response("Bir hata oluştu");
  }
}
1 Like