File: //opt/cwprads/cloudflare_apache_config
#!/usr/lib/cwprads/venv/bin/python3
import argparse
import fileinput
import os
import socket
import subprocess
from pathlib import Path
import requests
# Define the path of the configuration files
APACHE_CONF = Path("/usr/local/apache/conf/httpd.conf")
APACHE_CONF_DIR = Path("/usr/local/apache/conf.d/")
cf_apache_conf = APACHE_CONF_DIR / "cloudflare.conf"
httpd_path = Path("/usr/local/apache/bin/httpd")
def check_and_reload():
config_check = subprocess.run(
[httpd_path, "-t"],
stdout=subprocess.PIPE,
timeout=15.0,
check=False,
)
if config_check.returncode == 0:
print("Apache config is valid, restarting Apache")
os.system("systemctl restart httpd")
else:
print("Invalid Apache config. Not restarting Apache")
# Parse command-line arguments
parser = argparse.ArgumentParser()
parser.add_argument(
"--enable", help="Enable the configuration", action="store_true"
)
parser.add_argument(
"--disable", help="Disable the configuration", action="store_true"
)
args = parser.parse_args()
# Check if Apache is installed
APACHE_INSTALLED = httpd_path.exists()
if args.enable and APACHE_INSTALLED:
with fileinput.FileInput(APACHE_CONF, inplace=True) as file:
for line in file:
print(
line.replace(
"#LoadModule remoteip_module modules/mod_remoteip.so",
"LoadModule remoteip_module modules/mod_remoteip.so",
),
end="",
)
# Get Cloudflare's list of IPv4 addresses
response = requests.get("https://www.cloudflare.com/ips-v4", timeout=30)
cf_ip_list = response.text.split()
# Get the server's IP address
server_ip = socket.gethostbyname(socket.gethostname())
# Write the configuration to the Apache cloudflare.conf file
PROXIES = '\n'.join(f" RemoteIPTrustedProxy {ip}" for ip in cf_ip_list)
with open(cf_apache_conf, "w", encoding='utf-8') as file:
file.write(
f"""# Cloudflare https://www.cloudflare.com/ips
<IfModule mod_remoteip.c>
RemoteIPHeader X-Forwarded-For
RemoteIPInternalProxy 127.0.0.0/8 ::1 {server_ip}
{PROXIES}
</IfModule>
"""
)
# Check config and restart services
check_and_reload()
elif args.disable and APACHE_INSTALLED:
if os.path.exists(cf_apache_conf):
os.remove(cf_apache_conf)
print(f"{cf_apache_conf} removed.")
else:
print(f"{cf_apache_conf} does not exist.")
if os.path.exists(APACHE_CONF):
with fileinput.FileInput(APACHE_CONF, inplace=True) as file:
for line in file:
print(
line.replace(
"LoadModule remoteip_module modules/mod_remoteip.so",
"#LoadModule remoteip_module modules/mod_remoteip.so",
),
end="",
)
# Check config and restart services
check_and_reload()