forked from mrrfv/cloudflare-gateway-pihole-scripts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cf_gateway_rule_create.js
65 lines (57 loc) · 2.25 KB
/
cf_gateway_rule_create.js
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
require("dotenv").config();
const axios = require('axios');
const API_TOKEN = process.env.CLOUDFLARE_API_KEY;
const ACCOUNT_ID = process.env.CLOUDFLARE_ACCOUNT_ID;
const ACCOUNT_EMAIL = process.env.CLOUDFLARE_ACCOUNT_EMAIL;
// Function to read Cloudflare Zero Trust lists
async function getZeroTrustLists() {
const response = await axios.get(
`https://api.cloudflare.com/client/v4/accounts/${ACCOUNT_ID}/gateway/lists`,
{
headers: {
'Authorization': `Bearer ${API_TOKEN}`,
'Content-Type': 'application/json',
'X-Auth-Email': ACCOUNT_EMAIL,
'X-Auth-Key': API_TOKEN,
},
}
);
return response.data.result;
}
;(async() => {
const lists = await getZeroTrustLists();
const filtered_lists = lists.filter(list => list.name.startsWith('CGPS List'));
let wirefilter_expression = '';
// Build the wirefilter expression
for (const list of filtered_lists) {
wirefilter_expression += `any(dns.domains[*] in \$${list.id}) or `;
}
// Remove the trailing ' or '
if (wirefilter_expression.endsWith(' or ')) {
wirefilter_expression = wirefilter_expression.slice(0, -4);
}
wirefilter_expression = wirefilter_expression.trim().replace('\n', '');
if (!process.env.CI) console.log(`Firewall expression contains ${wirefilter_expression.length} characters, and checks against ${filtered_lists.length} filter lists.`)
const resp = await axios.request({
method: 'POST',
url: `https://api.cloudflare.com/client/v4/accounts/${ACCOUNT_ID}/gateway/rules`,
headers: {
'Authorization': `Bearer ${API_TOKEN}`,
'Content-Type': 'application/json',
'X-Auth-Email': ACCOUNT_EMAIL,
'X-Auth-Key': API_TOKEN,
},
data: {
"name": "CGPS Filter Lists",
"description": "Filter lists created by Cloudflare Gateway Pi-hole Scripts. Avoid editing this rule. Changing the name of this rule will break the script.",
"enabled": true,
"action": "block",
"filters": ["dns"],
"traffic": wirefilter_expression,
}
});
console.log('Success:', resp.data.success);
})();
async function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}