-
Notifications
You must be signed in to change notification settings - Fork 2
/
cloudflare.module
284 lines (249 loc) · 9.64 KB
/
cloudflare.module
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
<?php
/**
* @file
* Cloudflare module.
*/
define('CLOUDFLARE_URL_IPV4_RANGE', 'https://www.cloudflare.com/ips-v4');
define('CLOUDFLARE_ALWAYSONLINE_USER_AGENT', 'Mozilla/5.0 (compatible; CloudFlare-AlwaysOnline/1.0; +http://www.cloudflare.com/always-online) AppleWebKit/534.34');
/**
* Implements hook_config_info().
*/
function cloudflare_config_info() {
$prefixes['cloudflare.settings'] = array(
'label' => t('Cloudflare settings'),
'group' => t('Configuration'),
);
return $prefixes;
}
/**
* Implements hook_boot().
*
* Replace $_SERVER['REMOTE_ADDR'] with $_SERVER['HTTP_CF_CONNECTING_IP'] header
* Properly flag $_SERVER['HTTPS'] and set the base-url correctly if cloudflare
* is using flexible SSL.
*/
function cloudflare_boot() {
global $base_url, $conf;
$config = config('cloudflare.settings');
// This function might be invoked twice if flexible SSL support is enabled
// So make sure it is only ever run once.
static $run_once = TRUE;
if ($run_once) {
$run_once = FALSE;
}
else {
return;
}
// Only run if this is a CloudFlare request.
if (empty($_SERVER['HTTP_CF_RAY'])) {
return;
}
// Assign a proper IP address for end-client connecting via cloudflare using
// CF-Connecting-IP header.
if ($config->get('cloudflare_cf_connecting_ip') && !empty($_SERVER['HTTP_CF_CONNECTING_IP'])) {
if ($config->get('cloudflare_cf_connecting_ip') == 'trust') {
$connecting_ip = $_SERVER['REMOTE_ADDR'];
$_SERVER['ORIG_REMOTE_ADDR'] = $connecting_ip;
$_SERVER['REMOTE_ADDR'] = $_SERVER['HTTP_CF_CONNECTING_IP'];
$trusted = TRUE;
// Disable any furthur reverse proxy handling.
$conf['reverse_proxy'] = FALSE;
}
else {
$trusted = FALSE;
// If an array of known reverse proxy IPs is provided, then trust
// the CF header if request really comes from one of them or from a
// cloudflare IP.
$reverse_proxy_addresses = settings_get('reverse_proxy_addresses', array());
$connecting_ip = $_SERVER['REMOTE_ADDR'];
if (in_array($connecting_ip, $reverse_proxy_addresses) || cloudflare_ip_address_in_range($connecting_ip)) {
$_SERVER['ORIG_REMOTE_ADDR'] = $connecting_ip;
$_SERVER['REMOTE_ADDR'] = $_SERVER['HTTP_CF_CONNECTING_IP'];
$trusted = TRUE;
// Disable any furthur reverse proxy handling.
$conf['reverse_proxy'] = FALSE;
}
}
}
else {
// If we are not configured to use CF-Connecting-IP then use X-Forwarded-For
// instead This is the recommended method and is used by default.
$conf['reverse_proxy'] = TRUE;
// Remove CloudFlare IP addresses from X-Forwarded-For header.
// This ensures that the end-user IP address is never identified as a
// CloudFlare IP.
$reverse_proxy_header = settings_get('reverse_proxy_header', 'HTTP_X_FORWARDED_FOR');
if (!empty($_SERVER[$reverse_proxy_header])) {
$forwarded = explode(',', $_SERVER[$reverse_proxy_header]);
$forwarded = array_map('trim', $forwarded);
$good_ips = array();
foreach ($forwarded as $ip) {
if (!cloudflare_ip_address_in_range($ip)) {
$good_ips[] = $ip;
}
}
$_SERVER[$reverse_proxy_header] = implode(',', $good_ips);
}
}
backdrop_static_reset('ip_address');
// Properly flag the request as a HTTPS request if CloudFlare's flexible SSL
// is being used.
if (!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https' && empty($_SERVER['HTTPS'])) {
if ($trusted || in_array($connecting_ip, $reverse_proxy_addresses) || cloudflare_ip_address_in_range($connecting_ip, cloudflare_ip_ranges())) {
global $_cloudflare_ssl_handling;
if ($_cloudflare_ssl_handling) {
$_SERVER['HTTPS'] = 'on';
$conf['https'] = TRUE;
if (substr($base_url, 0, 7) === "http://") {
$base_url = 'https://' . substr($base_url, 7);
$GLOBALS['base_secure_url'] = $base_url;
$GLOBALS['is_https'] = TRUE;
}
}
else {
$parts = pathinfo(backdrop_get_filename('module', 'cloudflare'));
$include = 'require_once("' . $parts['dirname'] . '/cloudflare.https.inc");';
backdrop_set_message("CloudFlare SSL Error: CloudFlare HTTPS handling is not properly enabled. Add the following to your settings.php:<br/> <code style='font-family: monospace;'>$include</code>", 'error');
}
}
}
// Check for AlwaysOnline spider and set appropriate cache-control headers.
if (!empty($_SERVER['HTTP_USER_AGENT']) && $_SERVER['HTTP_USER_AGENT'] == CLOUDFLARE_ALWAYSONLINE_USER_AGENT) {
backdrop_add_http_header('Cache-Control', 'public, max-age=86400');
backdrop_add_http_header('Vary', 'User-Agent');
}
}
/**
* Implements hook_menu().
*/
function cloudflare_menu() {
$items['admin/config/system/cloudflare'] = array(
'title' => 'Cloudflare',
'page callback' => 'backdrop_get_form',
'page arguments' => array('cloudflare_admin'),
'access arguments' => array('administer cloudflare'),
'description' => 'Configure the Cloudflare settings.',
);
return $items;
}
/**
* Cloudflare_menu() page callback function.
*/
function cloudflare_admin() {
$config = config('cloudflare.settings');
$form = array();
$form['#config'] = 'cloudflare.settings';
$form['ip_address_handling'] = array(
'#type' => 'fieldset',
'#title' => 'IP Address Detection',
'#description' => t('<p>By default the X-Forwarded-For header is used determine the end-users IP address (default option). However, given the need to check forwarded IPs against a long list of trusted cloudflare IP ranges, this can increase load time and resource use on the server. </p>
<p>You can also choose to use CF-Connecting-IP and continue to verify the header against trusted IP addresses (second option). </p>
<p>The best option is to use CF-Connecting-IP and trust that the header is coming from a CloudFlare IP address (third option). While this option is the best in terms of resource usage and load time, for it to be secure your server either needs to only be accessible from CloudFlare, or have an upstream reverse proxy (such as varnish) that will verify that the request is coming from cloudflare if this header is present.</p>'),
);
$form['ip_address_handling']['cloudflare_cf_connecting_ip'] = array(
'#type' => 'radios',
'#options' => array(
'0' => t('Use X-Forwarded-For header'),
'verify' => t('Use CF-Connecting-IP header, but verify the header'),
'trust' => t('Use CF-Connecting-IP header, and trust the header'),
),
'#default_value' => $config->get('cloudflare_cf_connecting_ip'),
);
$form['cloudflare_api_email'] = array(
'#type' => 'textfield',
'#title' => t('E-mail address'),
'#description' => sprintf('%s %s.',
t('E-mail address for your Cloudflare account. You can find it on the'),
l(t('Communications Tab of Profile section'), 'https://dash.cloudflare.com/profile', array(
'attributes' => array(
'target' => '_blank',
),
)
)),
'#default_value' => $config->get('cloudflare_api_email'),
);
$form['cloudflare_api_key'] = array(
'#type' => 'textfield',
'#title' => t('API key'),
'#description' => sprintf('%s %s.',
t('API key for your Cloudflare account. You can find it on the'),
l(t('API Tokens Tab'), 'https://dash.cloudflare.com/profile/api-tokens', array(
'attributes' => array(
'target' => '_blank',
),
))
),
'#default_value' => state_get('cloudflare_api_key'),
);
$form['cloudflare'] = array(
'#type' => 'submit',
'#value' => 'Save',
);
return $form;
}
/**
* Admin submit handler.
*
* @todo Please document this function.
* @see http://drupal.org/node/1354
*/
function cloudflare_admin_submit($form, &$form_state) {
$form_values = $form_state['values'];
state_set('cloudflare_api_key', $form_values['cloudflare_api_key']);
$config = config('cloudflare.settings');
$config->set('cloudflare_cf_connecting_ip', $form_values['cloudflare_cf_connecting_ip']);
$config->set('cloudflare_api_email', $form_values['cloudflare_api_email']);
$config->save();
}
/**
* Get a list of cloudflare IP Ranges.
*/
function cloudflare_ip_ranges() {
if (cache_get('cloudflare_ip_ranges')) {
$cache = cache_get('cloudflare_ip_ranges');
return $cache->data;
}
else {
$ip_blocks = file_get_contents(CLOUDFLARE_URL_IPV4_RANGE);
if ($ip_blocks === FALSE) {
watchdog('cloudflare', 'Unable to fetch IP address information from cloudflare. Until resolved, IP address detection is non-functional.', NULL, WATCHDOG_ALERT);
return FALSE;
}
$cloudflare_ips = explode("\n", $ip_blocks);
$cloudflare_ips = array_filter($cloudflare_ips);
$cloudflare_ips = array_map('trim', $cloudflare_ips);
cache_set('cloudflare_ip_ranges', $cloudflare_ips);
return $cloudflare_ips;
}
}
/**
* Given an IP range like 8.8.8.0/24, check to see if an IP address is in it.
*/
function cloudflare_ip_address_in_range($checkip, $range = FALSE) {
if ($range === FALSE) {
$range = cloudflare_ip_ranges();
// Unable to determine cloudflare IP ranges.
if ($range === FALSE) {
return FALSE;
}
}
if (is_array($range)) {
foreach ($range as $ip_range) {
if (!empty($ip_range) && cloudflare_ip_address_in_range($checkip, $ip_range)) {
return TRUE;
}
}
return FALSE;
}
list($ip, $len) = explode('/', $range);
if (($min = ip2long($ip)) !== FALSE && !is_null($len)) {
$clong = ip2long($checkip);
$max = ($min | (1 << (32 - $len)) - 1);
if ($clong > $min && $clong < $max) {
return TRUE;
}
else {
return FALSE;
}
}
}