thảo luận Hướng dẫn dùng Cloudflare Zero Trust

được luôn
Ý mình là

1704299530567.png
 
sao thỉnh thoảng nó vẫn bị error lúc chạy nhỉ, lại phải vào rerun ko là ko chặn dc :canny: cảm giác từ sau khiđổi code token dạng mới là bị liên tục
 
Hướng dẫn sử dụng Cloudflare Worker để cập nhật IP match với Cloudflare qua DDNS:
Tại sao nên dùng: Bạn có thể set dns dạng 172.64.36.1, 172.64.36.2 thẳng vào router và sử dụng cho tất cả các thiết bị mạng có trong nhà mà không cần phải dùng DoH, DoT. Tốc độ truy vấn rất nhanh
  • Yêu cầu có ddns trỏ về IP nhà.
  • Cloudflare API, Cloudflare Email, API Key, Cloudflare ID (có hướng dẫn lấy tại #1)
(1) Tạo Worker và chỉnh sửa code theo code dưới đây:
OqargG6.png

Tiếp theo
D1c93dC.png

Tiếp theo
MtT1t73.png
Tiếp theo, nhập Name cho Worker
Tx5e8on.png

Kéo xuống cuối trang nhấn Deploy
EowsqQ5.png

Tiếp theo, nhấn Edit code
0aUoPq9.png

Tiếp theo, xoá tất cả các code, sửa code theo dưới đây:
IpczZnM.png

Điền các thông tin sau:
TZVbNKN.png

- Chỉnh sửa các thông tin: accountEmail, accountId (Cloudflare ID), apiKey, domain (DDNS của bạn).
Code:
addEventListener('scheduled', (event) => {
  event.waitUntil(handleRequest());
});

addEventListener('fetch', (event) => {
  return event.respondWith(handleRequest(event.request));
});

async function handleRequest(request) {
  const accountEmail = '';
  const accountId= '';
  const apiToken = '';
  const domain = '';
  const ip = await resolveDomain(domain);

  if (ip) {
    console.log(`The IP address of ${domain} is: ${ip}`);
    const locationId = await getLocationId(accountId, apiToken, accountEmail);
    if (locationId) {
      console.log(`The location ID is: ${locationId}`);
      const updateResult = await updateLocation(accountId, apiToken, locationId, ip, accountEmail);
      if (updateResult) {
        console.log("Update location successful:");
        console.log(`Location ID: ${updateResult.id}`);
        console.log(`Name: ${updateResult.name}`);
        console.log(`IP: ${updateResult.networks[0].network}`);
        console.log(`Subnet: ${updateResult.networks[0].network.split('/')[1]}`);
        console.log(`Created At: ${updateResult.created_at}`);
        console.log(`Updated At: ${updateResult.updated_at}`);
      } else {
        console.log("No location data found.");
      }
    } else {
      console.log("No locations found.");
    }
  } else {
    console.log(`Failed to resolve the IP address of ${domain}`);
  }

  return new Response('Worker execution completed', { status: 200 });
}

async function resolveDomain(domain) {
  const apiURL = 'https://dns.google.com/resolve';
  const queryURL = new URL(apiURL);
  queryURL.searchParams.append('name', domain);
  queryURL.searchParams.append('type', 'A');

  const response = await fetch(queryURL);
  const data = await response.json();

  if (data.Answer instanceof Array && data.Answer.length > 0) {
    const ipAddresses = data.Answer
      .filter(answer => answer.type === 1)
      .map(answer => answer.data);
    return ipAddresses[0] || null;
  } else {
    return null;
  }
}

async function getLocationId(accountId, apiToken, accountEmail) {

  const url = `https://api.cloudflare.com/client/v4/accounts/${accountId}/gateway/locations`;

  const response = await fetch(url, {
    headers: {
      'Authorization': `Bearer ${apiToken}`,
      'Content-Type': 'application/json',
      'X-Auth-Email': accountEmail,
      'X-Auth-Key': apiToken
    }
  });

  if (response.ok) {
    const data = await response.json();
    const result = data.result;
    return result.length > 0 ? result[0].id : null;
  } else {
    return null;
  }
}

async function updateLocation(accountId, apiToken, locationId, ip, accountEmail) {
  const url = `https://api.cloudflare.com/client/v4/accounts/${accountId}/gateway/locations/${locationId}`;

  const response = await fetch(url, {
    method: 'PUT',
    headers: {
      'Authorization': `Bearer ${apiToken}`,
      'Content-Type': 'application/json',
      'X-Auth-Email': accountEmail,
      'X-Auth-Key': apiToken
    },
    body: JSON.stringify({
      client_default: true,
      ecs_support: true,
      name: 'RouterZTE',
      networks: [
        { network: `${ip}/32` }
      ]
    })
  });

  if (response.ok) {
    const data = await response.json();
    return data.result || null;
  } else {
    return null;
  }
}
=> Save and deploy.
(2) Tạo Cron trigger để tự động chạy script cập nhật IP qua DDNS mỗi 1 phút (rất nhanh).
uxUmAud.png



(3) Chỉnh sửa giá trị Minutes là 1 (Chạy worker mỗi phút), sau đó nhấn Add Trigger
QAPmDJl.png


(4) Kết quả như thế này là hoàn tất:
oZXiESp.png


4. Cập nhật DNS cho thiết bị của bạn:
IPV4:

172.64.36.1
172.64.36.2
---
Máy tính:
rX0BoIt.png


Các thiết bị khác tương tự
Tốt nhất là đặt lên Router tổng để áp dụng cho tất cả các thiết bị trong nhà.
5. Kết thúc

Chúc các bạn cấu hình thành công. Sử dụng DNS dạng này cảm giác lướt web rất nhanh, không bị lỗi DoH (Mikrotik DoH không ổn định).
Kiểm tra xem đã chặn quảng cáo chưa:
Link 1:
Test Ad Block - Toolz (https://d3ward.github.io/toolz/adblock.html)
Link 2: AdBlock Test (https://iblockads.net/test)
Nhớ flush dns trước khi test nhé.
CMD: ipconfig /flushdns
*đã cập nhật ảnh lỗi
 
sao thỉnh thoảng nó vẫn bị error lúc chạy nhỉ, lại phải vào rerun ko là ko chặn dc :canny: cảm giác từ sau khiđổi code token dạng mới là bị liên tục
Lâu lắm rồi ko bị error, chắc do ít bộ lọc :D . thím để 2-3 bộ lọc nhỏ thôi, nó chặn vẫn tốt chán, như 1host lite hoặc hagezi light chẳng hạn
cái này thì mình làm r :D
Gia đình thì khuyến khích xài DoT/DoH lên thẳng đt cho tiện, đi đâu cũng bảo mật được
Modem mình để 8.8.8.8 với 9.9.9.11 để có ECS là chính
 
Mình vào CF --> Gateway --> DNS location copy cái DNS over TLS rồi cài luôn vào dns của điện thoại cũng đc. Ko cần phải cài thêm app 1.1.1.1

Nhưng cho mình hỏi
  • DNS đó cài đc cho tối đa bao nhiêu device nhỉ?
  • Mình thấy chặn các web người lớn rất tốt. Nhưng có 1 web ko thể nào chặn đc (vlxx .moe)
Dù mình vào block traffic gõ đúng domain đó vẫn ko chặn đc. Trong khi các web khác đều chặn oke
 
Mình vào CF --> Gateway --> DNS location copy cái DNS over TLS rồi cài luôn vào dns của điện thoại cũng đc. Ko cần phải cài thêm app 1.1.1.1

Nhưng cho mình hỏi
  • DNS đó cài đc cho tối đa bao nhiêu device nhỉ?
  • Mình thấy chặn các web người lớn rất tốt. Nhưng có 1 web ko thể nào chặn đc (vlxx .moe)
Dù mình vào block traffic gõ đúng domain đó vẫn ko chặn đc. Trong khi các web khác đều chặn oke
DoH hoặc DoT: không giới hạn thiết bị
Bạn vào Firewall policies -> Add a policy -> chọn Content categories In pỏn (hoặc chọn thêm mục khác) sau đó chọn Block
1704844972823.png
 
Hướng dẫn sử dụng Cloudflare Worker để cập nhật IP match với Cloudflare qua DDNS:
Tại sao nên dùng: Bạn có thể set dns dạng 172.64.36.1, 172.64.36.2 thẳng vào router và sử dụng cho tất cả các thiết bị mạng có trong nhà mà không cần phải dùng DoH, DoT. Tốc độ truy vấn rất nhanh
  • Yêu cầu có ddns trỏ về IP nhà.
  • Cloudflare API, Cloudflare Email, API Key, Cloudflare ID (có hướng dẫn lấy tại #1)
(1) Tạo Worker và chỉnh sửa code theo code dưới đây:
OqargG6.png

Tiếp theo
D1c93dC.png

Tiếp theo
MtT1t73.png
Tiếp theo, nhập Name cho Worker
Tx5e8on.png

Kéo xuống cuối trang nhấn Deploy
EowsqQ5.png

Tiếp theo, nhấn Edit code
0aUoPq9.png

Tiếp theo, xoá tất cả các code, sửa code theo dưới đây:
IpczZnM.png

Điền các thông tin sau:
TZVbNKN.png

- Chỉnh sửa các thông tin: accountEmail, accountId (Cloudflare ID), apiKey, domain (DDNS của bạn).
Code:
addEventListener('scheduled', (event) => {
  event.waitUntil(handleRequest());
});

addEventListener('fetch', (event) => {
  return event.respondWith(handleRequest(event.request));
});

async function handleRequest(request) {
  const accountEmail = '';
  const accountId= '';
  const apiToken = '';
  const domain = '';
  const ip = await resolveDomain(domain);

  if (ip) {
    console.log(`The IP address of ${domain} is: ${ip}`);
    const locationId = await getLocationId(accountId, apiToken, accountEmail);
    if (locationId) {
      console.log(`The location ID is: ${locationId}`);
      const updateResult = await updateLocation(accountId, apiToken, locationId, ip, accountEmail);
      if (updateResult) {
        console.log("Update location successful:");
        console.log(`Location ID: ${updateResult.id}`);
        console.log(`Name: ${updateResult.name}`);
        console.log(`IP: ${updateResult.networks[0].network}`);
        console.log(`Subnet: ${updateResult.networks[0].network.split('/')[1]}`);
        console.log(`Created At: ${updateResult.created_at}`);
        console.log(`Updated At: ${updateResult.updated_at}`);
      } else {
        console.log("No location data found.");
      }
    } else {
      console.log("No locations found.");
    }
  } else {
    console.log(`Failed to resolve the IP address of ${domain}`);
  }

  return new Response('Worker execution completed', { status: 200 });
}

async function resolveDomain(domain) {
  const apiURL = 'https://dns.google.com/resolve';
  const queryURL = new URL(apiURL);
  queryURL.searchParams.append('name', domain);
  queryURL.searchParams.append('type', 'A');

  const response = await fetch(queryURL);
  const data = await response.json();

  if (data.Answer instanceof Array && data.Answer.length > 0) {
    const ipAddresses = data.Answer
      .filter(answer => answer.type === 1)
      .map(answer => answer.data);
    return ipAddresses[0] || null;
  } else {
    return null;
  }
}

async function getLocationId(accountId, apiToken, accountEmail) {

  const url = `https://api.cloudflare.com/client/v4/accounts/${accountId}/gateway/locations`;

  const response = await fetch(url, {
    headers: {
      'Authorization': `Bearer ${apiToken}`,
      'Content-Type': 'application/json',
      'X-Auth-Email': accountEmail,
      'X-Auth-Key': apiToken
    }
  });

  if (response.ok) {
    const data = await response.json();
    const result = data.result;
    return result.length > 0 ? result[0].id : null;
  } else {
    return null;
  }
}

async function updateLocation(accountId, apiToken, locationId, ip, accountEmail) {
  const url = `https://api.cloudflare.com/client/v4/accounts/${accountId}/gateway/locations/${locationId}`;

  const response = await fetch(url, {
    method: 'PUT',
    headers: {
      'Authorization': `Bearer ${apiToken}`,
      'Content-Type': 'application/json',
      'X-Auth-Email': accountEmail,
      'X-Auth-Key': apiToken
    },
    body: JSON.stringify({
      client_default: true,
      ecs_support: true,
      name: 'RouterZTE',
      networks: [
        { network: `${ip}/32` }
      ]
    })
  });

  if (response.ok) {
    const data = await response.json();
    return data.result || null;
  } else {
    return null;
  }
}
=> Save and deploy.
(2) Tạo Cron trigger để tự động chạy script cập nhật IP qua DDNS mỗi 1 phút (rất nhanh).
uxUmAud.png



(3) Chỉnh sửa giá trị Minutes là 1 (Chạy worker mỗi phút), sau đó nhấn Add Trigger
QAPmDJl.png


(4) Kết quả như thế này là hoàn tất:
oZXiESp.png


4. Cập nhật DNS cho thiết bị của bạn:
IPV4:

172.64.36.1
172.64.36.2
---
Máy tính:
rX0BoIt.png


Các thiết bị khác tương tự
Tốt nhất là đặt lên Router tổng để áp dụng cho tất cả các thiết bị trong nhà.
5. Kết thúc

Chúc các bạn cấu hình thành công. Sử dụng DNS dạng này cảm giác lướt web rất nhanh, không bị lỗi DoH (Mikrotik DoH không ổn định).
Kiểm tra xem đã chặn quảng cáo chưa:
Link 1:
Test Ad Block - Toolz (https://d3ward.github.io/toolz/adblock.html)
Link 2: AdBlock Test (https://iblockads.net/test)
Nhớ flush dns trước khi test nhé.
CMD: ipconfig /flushdns
*đã cập nhật ảnh lỗi
2 cái IPv4 này lấy ở đâu thế bác, em nhập 2 cái này vào ko vào mạng đc nữa luôn :v
 
Last edited:
2 cái IPv4 này lấy ở đâu thế bác, em nhập 2 cái này vào ko vào mạng đc nữa luôn :v
cái này là code tự động update ip lên cloudflare zero rồi dùng 2 cái ipv4 mặc định 172.64.36.1, 172.64.36.2 add vào router hoặc pc không cần DOT, DOH
mình dùng cách1 như trên cũng bị lỗi xài cách 2 mod @Fioren thì ăn ngay
 
Back
Top