Cloudflare DNS Updater

Description

This program allows you to automatically update your Cloudflare DNS record and set your public IP address as a target.

Version and Patchnotes

Current version: 1.2.2.3
Release date: 12/20/2023

Patchnotes:

== Added ==
  * More detailed error messages in case of an error while updating your DNS records.
== Changed ==
  * Cleaned and optimized code.

Requirements

To run this program, you'll need some things (listed below).

  • Your OS must be Windows 8 or higher
  • You need a Cloudflare account (Account Plan doesn't matter)
  • You need your Domain
  • Your Nameservers must be pointing to Cloudflare.
  • An API token (it's important to use a token, not a key!)

Preparation

Cloudflare Sign up

  1. Click on the button “Sign up” in the upper right corner. (Location might change depending on Cloudflare's version)
  2. Enter your email address and a freshly generated password. (at least 8 chars, 1 special char, 1 number and no leading or trailing whitespaces)
  3. Check or uncheck the updates via the email option if you desire.
  4. Click on Sign up

Setup your Cloudflare account

  1. Click on the button labeled “Add a website or application”
  2. Now enter your domain (example.com) and click on continue.
  3. Select the Free plan at the bottom and click on Continue.
  4. Cloudflare will now check for existing records.
  5. You'll be asked to add more DNS records for your domain.
  6. Do so, and click on the button “Add record”.
  7. Select the record type depending on your public IP address. (A=IPv4 & AAA=IPv6)
  8. Enter a name (e.g. home or vpn)
  9. Once enter your public ip address manually. (What's my ip address?)
  10. Now click on save.
  11. Cloudflare will now check the ownership of this domain.
  12. Click on continue.
  13. Change your nameserver to the ones listed at point three. (Depends on domain provider, check their resources on how to).
  14. Click on continue.
  15. You'll now be prompted to the Quick Start Guide. Skip that by now by clicking on “Finish later”.

Get your Cloudflare Zone-ID

  1. At the Overview tab, locate the point “API” and copy your Zone ID. Just paste it into an empty text document so you have it ready later on.

Get your Cloudflare API token

  1. Click on the account icon in the upper right corner.
  2. Now click on “My Profile”.
  3. Click on API Tokens in the left sidebar.
  4. Click on the button labeled “Create Token”.
  5. Select the first template called “Edit zone DNS”.
  6. Now you need to select your zone (domain), listed at “Zone Resources”.
  7. Click on “Continue to summary”.
  8. And one last time, click on Create Token.
  9. You're now presented with your API token. Paste it into the same document as the Zone ID, just so you have it all in one place.

Download the program

  1. Head over to My offical website.
  2. Click on “Download (Win 64-Bit)”.
  3. Save the ZIP-Archive in your desired location. (CloudflareDNSUpdater_release.zip)

Unzipping the program

  1. Open up your file explorer and head over to the ZIP-Archive.
  2. Double-click on the archive.
  3. Click on “Extract all” in the upper menu of your File Explorer.
  4. Choose a location on your filesystem to save all extracted files. (e.g. C:\Program Files\DNS Updater)

Initial Setup

  1. Open up the executable in your directory. (CloudflareDNS.exe)
  2. Enter the setup mode by typing setup into the command prompt and hitting the enter key.
  3. You'll be asked some questions, answer them as follows.
  4. Enter your API Token.
  5. After successful verification, you'll be asked for your Zone-ID, so paste it in and hit enter.
  6. And again after successful verification, all existing records in your provided zone will be listed.
  7. Locate your desired record and copy the Record-ID.
  8. Paste the ID and once more, hit enter.

Arguments

By using the start argument autoupdate, the program will start and perform an automatic update before it closes automatically. This is helpful if you want to autorun the program e.g. with Windows Task Scheduler.

If the application doesn't close automatically, it's because of an error. The error message should tell you what's wrong.

Test

  1. Type update into the command prompt and hit your enter key.
  2. The program should print a success message.
  3. If so, head over to your Cloudflare dashboard. If not, check your record type (A for IPv4 or AAA for IPv6)
  4. Check your DNS record. After a successful cycle, your record should now have a comment attached. (Updated by PIN0L33KZ on: timestamp)

Automate update cycle

  1. Download the .XML task template from here.
  2. Open your Windows start menu and search for “Task Scheduler”.
  3. Click on “Import Task…” on the right-hand side.
  4. Select the downloaded .xml file as a template.
  5. Click on the “Change User or Group” button in the “General” tab.
  6. Enter your Windows account name and click on “Check Names”. Confirm with ok.
  7. Highlight the only available action “start program” in the “Actions” tab.
  8. Click on “Edit…”.
  9. Now click on “Browse…” and select your executable. (CloudflareDNS.exe)
  10. Confirm all windows by hitting ok.

API

The code snippets below, explain how we access the Cloudflare API with our program. Please refer to the cloudflare documentation for more details.

API-Class constructor

  1. public CloudflareAPI(string apiToken)
  2. {
  3. _apiToken = apiToken;
  4.  
  5. _httpClient = new HttpClient
  6. {
  7. BaseAddress = new Uri(@"https://api.cloudflare.com/client/v4/"),
  8. DefaultRequestHeaders =
  9. {
  10. Authorization = new AuthenticationHeaderValue("Bearer", _apiToken),
  11. Accept = { MediaTypeWithQualityHeaderValue.Parse("application/json") },
  12. UserAgent = { ProductInfoHeaderValue.Parse("AppName/1.0") }
  13. }
  14. };
  15. }

Validate Token

  1. public async Task<bool> ValidateTokenAsync()
  2. {
  3. try
  4. {
  5. string url = $"user/tokens/verify";
  6. string response = await _httpClient.GetStringAsync(url);
  7.  
  8. CloudflareApiResponse result = JsonSerializer.Deserialize<CloudflareApiResponse>(response);
  9.  
  10. return result.Result.Status == "active";
  11. }
  12. catch(Exception)
  13. {
  14. return false;
  15. }
  16. }

Validate Zone-ID

  1. public async Task<bool> ValidateZoneIDAsync(string zoneId)
  2. {
  3. try
  4. {
  5. string url = $"zones/{zoneId}";
  6. HttpResponseMessage response = await _httpClient.GetAsync(url);
  7.  
  8. return response.IsSuccessStatusCode;
  9. }
  10. catch(Exception)
  11. {
  12. return false;
  13. }
  14. }

Validate Record-ID

  1. public async Task<bool> ValidateRecordIDAsync(string zoneId, string recordId)
  2. {
  3. try
  4. {
  5. //Override record id if it's empty.
  6. if(recordId == "")
  7. {
  8. recordId = "null";
  9. }
  10.  
  11. string url = $"zones/{zoneId}/dns_records/{recordId}";
  12. HttpResponseMessage response = await _httpClient.GetAsync(url);
  13.  
  14. return response.IsSuccessStatusCode;
  15. }
  16. catch(Exception)
  17. {
  18. return false;
  19. }
  20. }

Get Records

  1. public async Task<List<CloudflareRecord>> GetDnsRecordsAsync(string zoneId)
  2. {
  3. string url = $"zones/{zoneId}/dns_records";
  4. string response = await _httpClient.GetStringAsync(url);
  5.  
  6. CloudflareApiDNSResponse result = JsonSerializer.Deserialize<CloudflareApiDNSResponse>(response);
  7.  
  8. return result?.Result ?? new List<CloudflareRecord>();
  9. }

Update Record

  1. public async Task<HttpResponseMessage> UpdateRecordAsync(string zoneId, string recordId, IPAddress publicIP)
  2. {
  3. try
  4. {
  5. string url = $"zones/{zoneId}/dns_records/{recordId}";
  6. HttpResponseMessage response = await _httpClient.GetAsync(url);
  7.  
  8. //Get record.
  9. string jsonResponse = await response.Content.ReadAsStringAsync();
  10. CloudflareApiDNSResponseSingleRecord record = JsonSerializer.Deserialize<CloudflareApiDNSResponseSingleRecord>(jsonResponse);
  11.  
  12. //Update record.
  13. record.Result.Content = publicIP.ToString();
  14. record.Result.Comment = "Updated by PIN0L33KZ on: " + DateTime.Now;
  15. string jsonRequest = JsonSerializer.Serialize<CloudflareRecord>(record.Result);
  16. response = await _httpClient.PutAsync(url, new StringContent(jsonRequest, Encoding.Default, "application/json"));
  17.  
  18. return response;
  19. }
  20. catch(Exception)
  21. {
  22. return null;
  23. }
  24. }



The source code is available on GitHub over here.
Marcello 11/11/2023 01:47

Back to top