| 1 |
<?php |
| 2 |
/** |
| 3 |
* Handles Cloudflare CIDR IP ranges. |
| 4 |
* |
| 5 |
* @package WP_Defender\Component\Trusted_Proxy_Preset |
| 6 |
*/ |
| 7 |
|
| 8 |
namespace WP_Defender\Component\Trusted_Proxy_Preset; |
| 9 |
|
| 10 |
use Calotes\Base\Component; |
| 11 |
use WP_Defender\Controller\Firewall; |
| 12 |
|
| 13 |
/** |
| 14 |
* Provides methods for managing Cloudflare CIDR IP ranges. |
| 15 |
*/ |
| 16 |
class Cloudflare_Proxy extends Component implements Trusted_Proxy_Preset_Strategy_Interface { |
| 17 |
|
| 18 |
public const PROXY_SLUG = 'cloudflare'; |
| 19 |
public const OPTION_NAME = 'wpdef_cloudflare_ips'; |
| 20 |
public const PROXY_API = 'https://api.cloudflare.com/client/v4/ips'; |
| 21 |
|
| 22 |
/** |
| 23 |
* Get Cloudflare CIDR IP ranges. |
| 24 |
* |
| 25 |
* @return array |
| 26 |
*/ |
| 27 |
public function get_ips(): array { |
| 28 |
$ip_ranges = get_site_option( self::OPTION_NAME, false ); |
| 29 |
|
| 30 |
if ( false === $ip_ranges ) { |
| 31 |
$ip_ranges = $this->update_ips(); |
| 32 |
} |
| 33 |
|
| 34 |
return is_array( $ip_ranges ) ? $ip_ranges : array(); |
| 35 |
} |
| 36 |
|
| 37 |
/** |
| 38 |
* Update Cloudflare CIDR IP ranges from API. |
| 39 |
* |
| 40 |
* @return bool|array |
| 41 |
*/ |
| 42 |
public function update_ips() { |
| 43 |
$response = wp_remote_get( self::PROXY_API ); |
| 44 |
|
| 45 |
if ( is_wp_error( $response ) ) { |
| 46 |
$this->log( 'Error fetching Cloudflare IPs: ' . $response->get_error_message(), Firewall::FIREWALL_LOG ); |
| 47 |
|
| 48 |
return false; |
| 49 |
} |
| 50 |
|
| 51 |
$body = wp_remote_retrieve_body( $response ); |
| 52 |
$data = json_decode( $body, true ); |
| 53 |
|
| 54 |
if ( ! $data || ! ( isset( $data['result']['ipv4_cidrs'] ) || isset( $data['result']['ipv6_cidrs'] ) ) ) { |
| 55 |
$this->log( 'Invalid response from Cloudflare API', Firewall::FIREWALL_LOG ); |
| 56 |
|
| 57 |
return false; |
| 58 |
} |
| 59 |
|
| 60 |
$ip_ranges = array_merge( |
| 61 |
$data['result']['ipv4_cidrs'] ?? array(), |
| 62 |
$data['result']['ipv6_cidrs'] ?? array() |
| 63 |
); |
| 64 |
|
| 65 |
// Store IP ranges in the database. |
| 66 |
update_site_option( self::OPTION_NAME, $ip_ranges ); |
| 67 |
|
| 68 |
return $ip_ranges; |
| 69 |
} |
| 70 |
|
| 71 |
/** |
| 72 |
* Delete Cloudflare CIDR IP ranges. |
| 73 |
* |
| 74 |
* @return bool |
| 75 |
*/ |
| 76 |
public function delete_ips(): bool { |
| 77 |
return delete_site_option( self::OPTION_NAME ); |
| 78 |
} |
| 79 |
} |
| 80 |
|