apache.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
  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 datetime
  10. import logging
  11. import os
  12. import subprocess
  13. import OpenSSL
  14. from amulib import helpers
  15. from amulib.cert_path_provider import CertPathProvider
  16. LOGGER = logging.getLogger("acme-updater")
  17. def run(cert_path_provider: CertPathProvider, config=None,
  18. named_key_path="/run/named/session.key", dns_server="localhost"):
  19. """
  20. Main method of the apache module, actually replaces the certificates,
  21. manages the service and writes TLSA records if necessary.
  22. :param cert_path_provider: provider of the certificate path
  23. :type cert_path_provider: CertPathProvider
  24. :param config: configuration for the module.
  25. :type config: dict
  26. :param named_key_path: path to the named session.key
  27. :type named_key_path: str
  28. :param dns_server: DNS server to use to create TLSA records
  29. :type dns_server: str
  30. """
  31. cert_renewed = False
  32. parsed_vhosts = []
  33. if config:
  34. vhosts_dir = config["vhosts_dir"]
  35. tlsa = config["tlsa"]
  36. exclude_vhosts = config["exclude_vhosts"]
  37. tlsa_exclude = config["tlsa_exclude"]
  38. else:
  39. # Default parameters based on best guesses
  40. vhosts_dir = "/etc/apache2/sites-enabled"
  41. tlsa = False
  42. exclude_vhosts = []
  43. tlsa_exclude = []
  44. for vhost in os.listdir(vhosts_dir):
  45. if vhost.endswith(".conf") and vhost not in exclude_vhosts:
  46. vhost_absolute = os.path.join(vhosts_dir, vhost)
  47. with open(vhost_absolute, "r") as vhost_file:
  48. parsed_vhosts.extend(helpers.parse_apache_vhost(vhost_file))
  49. for entry in parsed_vhosts:
  50. try:
  51. with open(entry[1], "r") as cert_file:
  52. cert_text = cert_file.read()
  53. except IOError:
  54. LOGGER.error("Error while opening cert file %s ", entry[1])
  55. else:
  56. x509_current_cert = OpenSSL.crypto.load_certificate(
  57. OpenSSL.crypto.FILETYPE_PEM, cert_text)
  58. if "Let's Encrypt" in x509_current_cert.get_issuer().__str__():
  59. fullchain_path = cert_path_provider.provide_fullchain_path(entry[0])
  60. try:
  61. with open(fullchain_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(fullchain_path, entry[1]):
  92. acme_key_path = cert_path_provider.provide_key_path(entry[0])
  93. if helpers.copy_file(acme_key_path, entry[2]):
  94. LOGGER.info(
  95. "Successfully renewed cert for %s",
  96. entry[0])
  97. cert_renewed = True
  98. else:
  99. LOGGER.error(
  100. "Renewal of cert for %s failed, "
  101. "please clean up manually and "
  102. "check the backup files!",
  103. entry[0])
  104. else:
  105. LOGGER.error("Renewal of cert for %s failed, "
  106. "please clean up manually and "
  107. "check the backup files!",
  108. entry[0])
  109. if cert_renewed:
  110. LOGGER.debug("Checking apache configuration")
  111. try:
  112. subprocess.check_call(["/usr/sbin/apache2ctl", "-t"])
  113. except subprocess.CalledProcessError:
  114. LOGGER.error("Error in apache configuration, will not restart the "
  115. "web server")
  116. else:
  117. try:
  118. subprocess.check_call(["/etc/init.d/apache2", "restart"])
  119. except subprocess.CalledProcessError:
  120. LOGGER.error("Apache restart failed!")
  121. else:
  122. LOGGER.info("Apache restarted successfully")