Files
CloudflareDDNS/README.md
T

371 lines
23 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# CloudflareDDNS
Update your *existing* Cloudflare DNS records with your current (dynamic) IP address via systemd timers and a (POSIX)
shell script.
## Contents
<!-- TOC -->
* [CloudflareDDNS](#cloudflareddns)
* [Contents](#contents)
* [Prerequisites](#prerequisites)
* [cfddns script](#cfddns-script)
* [Installation](#installation)
* [Usage](#usage)
* [Parameters](#parameters)
* [Cloudflare credentials file](#cloudflare-credentials-file)
* [File structure](#file-structure)
* [Bearer token](#bearer-token)
* [Zone ID](#zone-id)
* [cfddns systemd service unit](#cfddns-systemd-service-unit)
* [IP4 or IP6](#ip4-or-ip6)
* [Examples](#examples)
* [cfddns systemd timer unit](#cfddns-systemd-timer-unit)
* [Activation](#activation)
* [Logging](#logging)
* [JSON format](#json-format)
* [SYSLOG format](#syslog-format)
* [Systemd journal (journald)](#systemd-journal-journald)
* [Using Logwatch to monitor this script](#using-logwatch-to-monitor-this-script)
* [Using Logrotate to control log file size](#using-logrotate-to-control-log-file-size)
* [Final thoughts](#final-thoughts)
<!-- TOC -->
## Prerequisites
This script requires that `curl` and `jq` are installed. `curl` is used to interact with the Cloudflare API and `jq` is
used to efficiently and reliably construct/deconstruct the JSON strings and arrays returned by the Cloudflare API. If
you want to log to the system journal (journald), then `logger` must also be installed. In most cases you can install
these programs using your package manager running as root or via sudo:
```sh
# Debian/Ubuntu
sudo apt update && sudo apt install -y curl jq bsdutils
# Arch
sudo pacman -Sy curl jq logger
# Redhat/CentOS/Fedora
sudo dnf install curl jq util-linux
# Redhat/CentOS/Fedora (older versions)
sudo yum install curl jq util-linux
```
> While the script does *not* require root privileges, you will need sudo/root access to install the *systemd* service
> and timer.
## cfddns script
### Installation
I recommend putting this script in your */usr/local/bin* directory or somewhere else in your path so it's easy to run.
1. Copy the script file to your desired path and rename it if you want.
```Bash
sudo cp cfddns.sh /usr/local/bin/ # just copy it
sudo cp cfddns.sh /usr/local/bin/cloudflare-update.sh # copy and rename (choose any name)
```
2. Make it executable:
```Bash
sudo chmod +x /usr/local/bin/cfddns.sh
```
> Note: You can rename *cfddns.sh* to anything you want, the script will automatically use its current name. However,
> you **must** manually update the systemd service file (*cfddns.service*) `ExecStart` line
> as [explained below](#cfddns-script).
### Usage
If you run the script with no parameters, it will display the help screen. The script accepts several parameters with
only one (1) being required. The parameters are summarized below. You can access the help screen and example usage
screens by running:
```Bash
cfddns.sh --help # display help screen
cfddns.sh --examples # show script usage examples
```
#### Parameters
| Parameter | Description | Default | Required? |
|------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------|:---------:|
| -r<br>--record<br>--records | The fully qualified hostname(s) that should be updated with new IP addresses. You can supply a comma-delimited list (no spaces) or just one. Note that the script can only update *either* A *or* AAAA records during a single run so you may need to batch your hostnames, depending on your set-up.<br>**N.B. This script will only update *existing* host records, it will _not_ create new ones!** | none | YES |
| -c<br>--cred<br>--creds<br>--credentials<br>-f | Full path to your CloudFlare credentials file. This file contains your access token and zone id. See the [relevant section](#cloudflare-credentials-file) of this readme for more information. | scriptPath/cloudflare.credentials | NO |
| -i<br>--ip<br>--ip-address<br>-a<br>--address | The IP address that should be used to update Host A/AAAA records. If you omit this value, the script will attempt to auto-detect your public IP4/IP6 address and use that as appropriate. Use this option to manually force a specific IP to be used or when auto-detection fails. Note that the script does *not* check your IP addresses for correctness or proper form! | IP4 auto-detect | NO |
| -4<br>--ip4<br>--ipv4 | Update Host A records only (IP4). The script can only update *either* A *or* AAAA records in a single run. If you specify this and also use the IP6 mode switch, the most recent one will take effect. | Enabled, update A records | NO |
| -6<br>--ip6<br>--ipv6 | Update Host AAAA records only (IP6). The script can only update *either* A *or* AAAA records in a single run. If you specify this and also use the IP4 mode switch, the most recent one will take effect. | Disabled, update A records | NO |
| | | | |
| --log-file | Generate a log file and save it in the specified location. Only specify this option if you want to save the log file in a non-default location. If you want to save the log in the default location, omit this option. Recommend */var/log/scriptName.log* | scriptPath/scriptName.log | NO |
| --log-journal | Log to the system journal (journald) instead of a log file. Log entries are automatically tagged 'CFDDNS' for easier filtering. Format tags do NOT apply when using this option. Use `json` or `pretty-json` with `journalctl` to see all logged properties. | Disabled, write to log file | NO |
| --log-console | Write log entries to the console (stdout) instead of a log file. Using `--fmt-syslog` with this option is strongly recommended since JSON is difficult to read on the console. | Disabled, write to log file | NO |
| --no-log | Do *not* write a log file, write to the journal, or output to the console. You will not have **any** feedback from the script if you run in this mode so you will not know if updates were successful or not. Im not really sure why youd want this option, but its available. | Disabled, write to log file | NO |
| | | | |
| --fmt-json | Write the log file or console output in a structured *Compact Log Event Format (CLEF)* JSON format. You will probably need a log viewer to meaningfully parse the logs. | Enabled | NO |
| --fmt-syslog | Write the log file or console output in a modified plain-text *syslog* style. This option is recommended when using `--log-console` or if you need easily readable log files. While all log entries are *consistent* using this format, they are not *structured*. | Disabled, just JSON format | NO |
| | | | |
| -h<br>--help<br>-? | Display built-in help screen explaining these same parameters. | | |
| --examples | Display some usage examples. Sometimes it's easier to understand by seeing rather than reading. | | |
## Cloudflare credentials file
This repo includes a sample credentials file (*cloudflare.credentials* at the root of the repo) with pretty
self-explanatory variable names. The script reads this file to get the credentials it needs to connect to your
Cloudflare account and update DNS entries. It should be noted that the script is designed to use a *bearer token* and
**not** your username/password or your Global API token! Lets break this down in case things are a little fuzzy
still...
### File structure
The file is a basic shell script variables file. Make sure you **do not** put spaces between the variable name, equal
sign and the value. Also, **do not** add any executable code since it will be run! The file should contain values for
the following two variables:
| Variable | Value |
|----------|----------------------------------------------------------------------------------------------|
| cfKey | The bearer token granting access to *edit* the DNS records of the zone (domain) in question. |
| cfZoneId | The Cloudflare Zone ID of the zone (domain) you wish to update. |
You can add comments if youd like since the script will ignore them. In the end, your file should look something like
this, but obviously with your data instead of this nonsense sample information:
```ini
#
# Cloudflare token for my.domain.tld
#
cfKey=_dLuyyRNaKN8SLG4-csmNYYfC39nnCmPVA7aYUJj
cfZoneId=83d564234134513245311b23412331dd
```
You can save the file as anything you like and anywhere youd like as long as you inform the script of its location
using the `--credentials` parameter. By default, the script will look for a file named *cloudflare.credentials* at the
same path as the script.
Please remember that this file basically contains a password! As a result, it should be protected and access limited to
the root account:
```bash
chown root:root /path/to/cloudflare.credentials
chmod 600 /path/to/cloudflare.credentials
```
### Bearer token
I chose to use an API bearer token instead of a username/password or Global API token for security reasons. Your
username/password and Global API token provide unfettered access to your account, so if anyone gets hold of them, they
can do anything to your account. An API bearer token, by contrast, only permits actions you explicitly authorize when
you create it, and you can revoke it at any time. Therefore, I suggest making a bearer token that is based on the
“Edit zone DNS” template and restricted to the specific domain/zone you wish to update. Cloudflare provides
an [excellent article](https://support.cloudflare.com/hc/en-us/articles/200167836-Managing-API-Tokens-and-Keys) on how
to generate this token.
> N.B. This is a breaking change from previous versions of this script!
### Zone ID
This is required by the Cloudflare API so it knows which zone you are editing and can check the permissions of the
bearer token. This script only caters to one zone, so likely only one domain per configuration file. If you need to
update multiple zones, you can have multiple configuration files and call them as required on separate invocations of
the script.
To get your Zone ID, log into your Cloudflare account and open the domain in question. On the overview page, scroll down
a bit and look to the right. You will see your Zone ID listed there. Copy that string into your configuration file.
## cfddns systemd service unit
For the easiest implementation, this file should be copied to your */etc/systemd/system* directory. If you change the
name of the *cfddns.sh* file, you must update the filename in the `ExecStart` line as shown below:
````Ini
...
[Service]
Type=oneshot
ExecStart=/full/path/to/your/renamed.file -parameter1 -parameter2 -parameter...
...
````
### IP4 or IP6
The cfddns.service file includes two *ExecStart* lines, one without a specified IP-protocol parameter (default IP4) and
the other with the -6 (IP6) parameter. The service will run the cfddns&#46;sh script in default (IP4) mode with
specified parameters first and then will run the script again in IP6 mode with specified parameters.
*Note: The parameters *can be different* in each case.*
> **N.B.** This is a `oneshot` type systemd unit-file, so we can have multiple `ExecStart` lines.
#### Examples
1. **Only update A records**
Update the `A` record for *mail.example.com* with the current auto-detected public IP4 address of this machine and
log in JSON format (default) to */var/log/cfddns.log*. Note our Cloudflare credentials file is located in the *root
user's home* directory.
```Ini
[Service]
Type=oneshot
ExecStart=/usr/local/bin/cfddns.sh -c /root/cloudflare.credentials -r mail.example.com --log-file /var/log/cfddns.log
...
```
2. **Only update AAAA records**
Update `AAAA` records for *git.example.com* and *mail.example.com* with the current auto-detected public IP6 address
of this machine. The log will be stored in the same directory as the script file (default) and will be
JSON-formatted (default). In this case, the Cloudflare credentials file is located in */home/johndoe*.
```Ini
[Service]
Type=oneshot
ExecStart=/usr/local/bin/cfddns.sh -6 -c /home/johndoe/cloudflare.credentials -r git.example.com,mail.example.com
...
```
3. **Update A records then AAAA records**
Update the `A` record for *mail.example.com* with the auto-detected public IP4 address of this machine. Then, update
`AAAA` records for both *mail.example.com* and *git.example.com* with the *specified IP6 address*. In both cases, we
are logging to the system journal (journald). Also notice that the Cloudflare credentials file is located in
different
places for each script call.
```Ini
[Service]
Type=oneshot
# update IP4 addresses
ExecStart=/usr/local/bin/cfddns.sh -c /dir1/account.cf -r mail.example.com --log-journal
# update IP6 addresses
ExecStart=/usr/local/bin/cfddns.sh -6 -c /dir2/cloudflare.details -r mail.example.com,git.example.com --ip fd3f:e6db:9817:df84::a001 --log-journal
...
```
## cfddns systemd timer unit
Again, for the easiest configuration, this file should be copied to your */etc/systemd/system* directory. This timer
file unit tells your system how often to call the *cfddns.service* file which runs the *cfddns.sh* script. By default,
the timer is set for 5 minutes after the system boots up (to allow for other processes to initialize even on slower
systems like a RasPi) and is then run every 15 minutes thereafter. Remember when setting your timer that Cloudflare
limits API calls to 1200 every 5 minutes.
You can change the timer by modifying the relevant section of the *cfddns.timer* file:
```Ini
[Timer]
OnBootSec=5min
OnUnitActiveSec=15min
```
*OnBootSec* is how long to wait after the system boots up before executing the *cfddns.service*. *OnUnitActiveSec* will
then wait the specified time from that first (after boot) call or after the timer is explicitly started before calling
*cfddns.service* again. I recommend setting OnUnitActiveSec to a low value (like 2 minutes) for testing, then setting it
to a more reasonable time (like 15 minutes) after everything is working.
Remember to reload `systemd` after youve copied both the systemd unit and this timer unit. Run the following as root or
via sudo:
```sh
systemctl daemon-reload
```
### Activation
You can start the timer system immediately via *systemctl*
```Bash
systemctl start cfddns.timer
```
and can enable it to start automatically on boot by typing
```Bash
systemctl enable cfddns.timer
```
You can check the status of the timer via systemctl also
```Bash
systemctl status cfddns.timer
```
It is NOT necessary to enable/start the *cfddns.service*, only the timer needs to be active.
Also remember that if you make changes to settings like `OnUnitActiveSec` while testing, or after testing is complete,
you *must* reload the systemd daemon! It will restart the appropriate units for you, and your new settings will take
effect immediately.
## Logging
The script logs every major action it takes and provides details on any errors it encounters in the log file. Refer
to the [parameters section](#parameters) for details about setting log location and name. Starting in version 3.0, the
entire logging system outputs structured **JSON** by default.
> PLEASE remember to review your current log review/parsing system if upgrading from previous versions since this is a
> **major** change to how logging works.
**IMPORTANT:** This script uses the same log file for its output (unless you specify a different log file each time it
is run) therefore, you should avoid switiching formats within existing log files. For example, if you are using the
default log file, and run the script once with `--fmt-syslog` then switch to the default `--fmt-json`, parsing your log
will become very difficult. If you are switching log formats, it is best to start with a fresh log file.
### JSON format
This is the default logging format since it allows for easy parsing and filtering of log entries while still retaining a
structured format. I chose to implement a modified [Compact Log Event Format (CLEF)](https://clef-json.org) with the
following format for every message (expanded for readability, the log file is not 'pretty-printed'):
```json
{
"@t": "ISO-8601 timestamp",
"@m": "message describing the event",
"@l": "log level",
"hostname": "hostname of the machine executing the script",
"programName": "CFDDNS",
"pid": "PID of the process executing the script",
"status": "status of the operation being logged",
"operation": "short-name of the operation being logged",
"code": "numeric 'exit code' of the operation being logged"
}
```
### SYSLOG format
The SYSLOG format (`--fmt-syslog`) is a modified version of the typical plain-text *nix syslog format. This format is
useful when outputting the log to the console or when you need a very human-friendly format for the log files since you
will be manually parsing them. While the plain-text format is not *structured*, it is *consistent*:
```text
ISO-8601 timestamp hostname CFDDNS[pid]: LOG_LEVEL STATUS MESSAGE (OPERATION:CODE)
```
### Systemd journal (journald)
When using the `--log-journal` option, all logging will be sent to `journald` using its format. All log messages are
tagged `CFDDNS` to make filtering easier. Additional information logged with each entry can be exposed using the `json`
or `json-pretty` output options for `journalctl`.
### Using Logwatch to monitor this script
If you are using the Logwatch package to monitor your system, see the README in the */etc/logwatch* folder for details
about the pre-configured service files already done for you :-)
### Using Logrotate to control log file size
Logrotate is pre-installed on most linux distributions and is a great way to automatically rotate your log
files and control how many old logs you keep on your system so they don't accumulate and eat up your disk space. I've
included a sample configuration file you can copy to your */etc/logrotate.d/* folder. This file is set up to rotate your
logs once a week, keep 3 weeks worth of history (compressed) and delete all logs older than that. The configuration file
is located in this git archive at */etc/logrotate.d/cfddns* and is fully commented to help you customize it to suit your
needs.
## Final thoughts
Hopefully, this helps you with an easy and reliable way to update your Cloudflare DNS entries with a dynamic IP address.
Please feel free to comment and provide feedback and suggestions to make this script better!
Please check out my blog at [https://mytechiethoughts.com](https://mytechiethoughts.com) where I tackle problems like
this all the time and find free/inexpensive solutions to tech problems.