apache.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143
  1. # This file is part of acme-updater, written by Helmut Pozimski 2016-2017.
  2. #
  3. # stov is free software: you can redistribute it and/or modify
  4. # it under the terms of the GNU General Public License as published by
  5. # the Free Software Foundation, version 2 of the License.
  6. #
  7. # stov is distributed in the hope that it will be useful,
  8. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. # GNU General Public License for more details.
  11. #
  12. # You should have received a copy of the GNU General Public License
  13. # along with stov. If not, see <http://www.gnu.org/licenses/>.
  14. # -*- coding: utf8 -*-
  15. """
  16. Contains the apache module which takes care of maintaining the apache 2 SSL
  17. certificates.
  18. """
  19. import logging
  20. import os
  21. import datetime
  22. import subprocess
  23. from amulib import helpers
  24. import OpenSSL
  25. LOGGER = logging.getLogger("acme-updater")
  26. def run(config=None, acme_dir="/var/lib/acme",
  27. named_key_path="/run/named/session.key"):
  28. """
  29. Main method of the apache module, actually replaces the certificates,
  30. manages the service and writes TLSA records if necessary.
  31. :param config: configuration for the module.
  32. :type config: dict
  33. :param acme_dir: path to the acme state dir
  34. :type acme_dir: str
  35. :param named_key_path: path to the named session.key
  36. :type named_key_path: str
  37. """
  38. cert_renewed = False
  39. parsed_vhosts = []
  40. if config:
  41. vhosts_dir = config["vhosts_dir"]
  42. tlsa = config["tlsa"]
  43. exclude_vhosts = config["exclude_vhosts"]
  44. tlsa_exclude = config["tlsa_exclude"]
  45. else:
  46. # Default parameters based on best guesses
  47. vhosts_dir = "/etc/apache2/sites-enabled"
  48. tlsa = False
  49. exclude_vhosts = []
  50. tlsa_exclude = []
  51. for vhost in os.listdir(vhosts_dir):
  52. if vhost.endswith(".conf") and vhost not in exclude_vhosts:
  53. vhost_absolute = os.path.join(vhosts_dir, vhost)
  54. with open(vhost_absolute, "r") as vhost_file:
  55. parsed_vhosts.extend(helpers.parse_apache_vhost(vhost_file))
  56. for entry in parsed_vhosts:
  57. try:
  58. with open(entry[1], "r") as cert_file:
  59. cert_text = cert_file.read()
  60. except IOError:
  61. LOGGER.error("Error while opening cert file %s ", entry[1])
  62. else:
  63. x509_current_cert = OpenSSL.crypto.load_certificate(
  64. OpenSSL.crypto.FILETYPE_PEM, cert_text)
  65. if "Let's Encrypt" in x509_current_cert.get_issuer().__str__():
  66. acme_cert_path = os.path.join(acme_dir, "live", entry[0],
  67. "cert")
  68. try:
  69. with open(acme_cert_path, "r") as acme_cert_file:
  70. acme_cert_text = acme_cert_file.read()
  71. except IOError:
  72. LOGGER.error("Could not open certificate for %s in acme "
  73. "state directory", entry[0])
  74. else:
  75. x509_acme_cert = OpenSSL.crypto.load_certificate(
  76. OpenSSL.crypto.FILETYPE_PEM, acme_cert_text
  77. )
  78. expiry_date = \
  79. x509_acme_cert.get_notAfter().decode("utf-8")
  80. expiry_datetime = helpers.parse_asn1_time(expiry_date)
  81. if expiry_datetime < datetime.datetime.utcnow():
  82. LOGGER.warning(
  83. "Certificate for %s is expired and no newer "
  84. "one is available, bailing out!", entry[0])
  85. else:
  86. serial_current_cert = \
  87. x509_current_cert.get_serial_number()
  88. serial_acme_cert = x509_acme_cert.get_serial_number()
  89. if serial_current_cert == serial_acme_cert:
  90. LOGGER.debug("Cert for %s matches with the one "
  91. "installed, nothing to do.", entry[1])
  92. else:
  93. if tlsa:
  94. for domain in entry[3]:
  95. if domain not in tlsa_exclude:
  96. helpers.create_tlsa_records(
  97. domain, "443", x509_acme_cert,
  98. named_key_path)
  99. if helpers.copy_file(acme_cert_path, entry[1]):
  100. acme_key_path = os.path.join(acme_dir,
  101. "live", entry[0],
  102. "privkey")
  103. if helpers.copy_file(acme_key_path, entry[2]):
  104. LOGGER.info(
  105. "Successfully renewed cert for %s",
  106. entry[0])
  107. cert_renewed = True
  108. else:
  109. LOGGER.error(
  110. "Renewal of cert for %s failed, "
  111. "please clean up manually and "
  112. "check the backup files!",
  113. entry[0])
  114. else:
  115. LOGGER.error("Renewal of cert for %s failed, "
  116. "please clean up manually and "
  117. "check the backup files!",
  118. entry[0])
  119. if cert_renewed:
  120. LOGGER.debug("Checking apache configuration")
  121. try:
  122. subprocess.check_call(["/usr/sbin/apache2ctl", "-t"])
  123. except subprocess.CalledProcessError:
  124. LOGGER.error("Error in apache configuration, will not restart the "
  125. "web server")
  126. else:
  127. try:
  128. subprocess.check_call(["/etc/init.d/apache2", "restart"])
  129. except subprocess.CalledProcessError:
  130. LOGGER.error("Apache restart failed!")
  131. else:
  132. LOGGER.info("Apache restarted successfully")