apache.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  1. # SPDX-FileCopyrightText: 2016-2023 Helmut Pozimski <helmut@pozimski.eu>
  2. #
  3. # SPDX-License-Identifier: GPL-2.0-only
  4. # -*- coding: utf8 -*-
  5. """
  6. Contains the apache module which takes care of maintaining the apache 2 SSL
  7. certificates.
  8. """
  9. import logging
  10. import os
  11. import datetime
  12. import subprocess
  13. from amulib import helpers
  14. import OpenSSL
  15. LOGGER = logging.getLogger("acme-updater")
  16. def run(config=None, acme_dir="/var/lib/acme",
  17. named_key_path="/run/named/session.key", dns_server="localhost"):
  18. """
  19. Main method of the apache module, actually replaces the certificates,
  20. manages the service and writes TLSA records if necessary.
  21. :param config: configuration for the module.
  22. :type config: dict
  23. :param acme_dir: path to the acme state dir
  24. :type acme_dir: str
  25. :param named_key_path: path to the named session.key
  26. :type named_key_path: str
  27. :param dns_server: DNS server to use to create TLSA records
  28. :type dns_server: str
  29. """
  30. cert_renewed = False
  31. parsed_vhosts = []
  32. if config:
  33. vhosts_dir = config["vhosts_dir"]
  34. tlsa = config["tlsa"]
  35. exclude_vhosts = config["exclude_vhosts"]
  36. tlsa_exclude = config["tlsa_exclude"]
  37. else:
  38. # Default parameters based on best guesses
  39. vhosts_dir = "/etc/apache2/sites-enabled"
  40. tlsa = False
  41. exclude_vhosts = []
  42. tlsa_exclude = []
  43. for vhost in os.listdir(vhosts_dir):
  44. if vhost.endswith(".conf") and vhost not in exclude_vhosts:
  45. vhost_absolute = os.path.join(vhosts_dir, vhost)
  46. with open(vhost_absolute, "r") as vhost_file:
  47. parsed_vhosts.extend(helpers.parse_apache_vhost(vhost_file))
  48. for entry in parsed_vhosts:
  49. try:
  50. with open(entry[1], "r") as cert_file:
  51. cert_text = cert_file.read()
  52. except IOError:
  53. LOGGER.error("Error while opening cert file %s ", entry[1])
  54. else:
  55. x509_current_cert = OpenSSL.crypto.load_certificate(
  56. OpenSSL.crypto.FILETYPE_PEM, cert_text)
  57. if "Let's Encrypt" in x509_current_cert.get_issuer().__str__():
  58. acme_cert_path = os.path.join(acme_dir, "live", entry[0],
  59. "fullchain")
  60. try:
  61. with open(acme_cert_path, "r") as acme_cert_file:
  62. acme_cert_text = acme_cert_file.read()
  63. except IOError:
  64. LOGGER.error("Could not open certificate for %s in acme "
  65. "state directory", entry[0])
  66. else:
  67. x509_acme_cert = OpenSSL.crypto.load_certificate(
  68. OpenSSL.crypto.FILETYPE_PEM, acme_cert_text
  69. )
  70. expiry_date = \
  71. x509_acme_cert.get_notAfter().decode("utf-8")
  72. expiry_datetime = helpers.parse_asn1_time(expiry_date)
  73. if expiry_datetime < datetime.datetime.utcnow():
  74. LOGGER.warning(
  75. "Certificate for %s is expired and no newer "
  76. "one is available, bailing out!", entry[0])
  77. else:
  78. serial_current_cert = \
  79. x509_current_cert.get_serial_number()
  80. serial_acme_cert = x509_acme_cert.get_serial_number()
  81. if serial_current_cert == serial_acme_cert:
  82. LOGGER.debug("Cert for %s matches with the one "
  83. "installed, nothing to do.", entry[1])
  84. else:
  85. if tlsa:
  86. for domain in entry[3]:
  87. if domain not in tlsa_exclude:
  88. helpers.create_tlsa_records(
  89. domain, "443", x509_acme_cert,
  90. named_key_path, dns_server)
  91. if helpers.copy_file(acme_cert_path, entry[1]):
  92. acme_key_path = os.path.join(acme_dir,
  93. "live", entry[0],
  94. "privkey")
  95. if helpers.copy_file(acme_key_path, entry[2]):
  96. LOGGER.info(
  97. "Successfully renewed cert for %s",
  98. entry[0])
  99. cert_renewed = True
  100. else:
  101. LOGGER.error(
  102. "Renewal of cert for %s failed, "
  103. "please clean up manually and "
  104. "check the backup files!",
  105. entry[0])
  106. else:
  107. LOGGER.error("Renewal of cert for %s failed, "
  108. "please clean up manually and "
  109. "check the backup files!",
  110. entry[0])
  111. if cert_renewed:
  112. LOGGER.debug("Checking apache configuration")
  113. try:
  114. subprocess.check_call(["/usr/sbin/apache2ctl", "-t"])
  115. except subprocess.CalledProcessError:
  116. LOGGER.error("Error in apache configuration, will not restart the "
  117. "web server")
  118. else:
  119. try:
  120. subprocess.check_call(["/etc/init.d/apache2", "restart"])
  121. except subprocess.CalledProcessError:
  122. LOGGER.error("Apache restart failed!")
  123. else:
  124. LOGGER.info("Apache restarted successfully")