mirror of
https://github.com/certbot/certbot.git
synced 2026-03-13 14:12:11 -04:00
Class inheritance based approach to distro specific overrides.
How it works:
The certbot-apache plugin entrypoint has been changed to entrypoint.ENTRYPOINT which is a variable containing appropriate override class for system, if available.
Override classes register themselves using decorator override.register() which takes a list of distribution fingerprints (ID & LIKE variables in /etc/os-release, or platform.linux_distribution() as a fallback). These end up as keys in dict override.OVERRIDE_CLASSES and values for the keys are references to the class that called the decorator, hence allowing self-registration of override classes when they are imported. The only file importing these override classes is entrypoint.py, so adding new override classes would need only one import in addition to the actual override class file.
Generic changes:
Parser initialization has been moved to separate class method, allowing easy override where needed.
Cleaned up configurator.py a bit, and moved some helper functions to newly created apache_util.py
Split Debian specific code from configurator.py to debian_override.py
Changed define_cmd to apache_cmd because the parameters are for every distribution supporting this behavior, and we're able to use the value to build the additional configuration dump commands.
Moved add_parser_mod() from configurator to parser add_mod()
Added two new configuration dump parsing methods to update_runtime_variables() in parser: update_includes() and update_modules().
Changed init_modules() in parser to accommodate the changes above. (ie. don't throw existing self.modules out).
Moved OS based constants to their respective override classes.
Refactored configurator class discovery in tests to help easier test case creation using distribution based override configurator class.
tests.util.get_apache_configurator() now takes keyword argument os_info which is string of the desired mock OS fingerprint response that's used for picking the right override class.
This PR includes two major generic additions that should vastly improve our parsing accuracy and quality:
Includes are parsed from config dump from httpd binary. This is mandatory for some distributions (Like OpenSUSE) to get visibility over the whole configuration tree because of Include statements passed on in command line, and not via root httpd.conf file.
Modules are parsed from config dump from httpd binary. This lets us jump into correct IfModule directives if for some reason we have missed the module availability (because of one being included on command line or such).
Distribution specific changes
Because of the generic changes, there are two distributions (or distribution families) that do not provide such functionality, so it had to be overridden in their respective override files. These distributions are:
CentOS, because it deliberately limits httpd binary stdout using SELinux as a feature. We are doing opportunistic config dumps here however, in case SELinux enforcing is off.
Gentoo, because it does not provide a way to invoke httpd with command line parsed from its specific configuration file. Gentoo relies heavily on Define statements that are passed over from APACHE2_OPTS variable /etc/conf.d/apache2 file and most of the configuration in root Apache configuration are dependent on these values.
Debian
Moved the Debian specific parts from configurator.py to Debian specific override.
CentOS
Parsing of /etc/sysconfig/httpd file for additional Define statements. This could hold other parameters too, but parsing everything off it would require a full Apache lexer. For CLI parameters, I think Defines are the most common ones. This is done in addition of opportunistic parsing of httpd binary config dump.
Added CentOS default Apache configuration tree for realistic test cases.
Gentoo
Parsing Defines from /etc/conf.d/apache2 variable APACHE2_OPTS, which holds additional Define statements to enable certain functionalities, enabling parts of the configuration in the Apache2 DOM. This is done instead of trying to parse httpd binary configuration dumps.
Added default Apache configuration from Gentoo to testdata, including /etc/conf.d/apache2 file for realistic test cases.
* Distribution specific override functionality based on class inheritance
* Need to patch get_systemd_os_like to as travis has proper os-release
* Added pydoc
* Move parser initialization to a method and fix Python 3 __new__ errors
* Parser changes to parse HTTPD config
* Try to get modules and includes from httpd process for better visibility over the configuration
* Had to disable duplicate-code because of test setup (PyCQA/pylint/issues/214)
* CentOS tests and linter fixes
* Gentoo override, tests and linter fixes
* Mock the process call in all the tests that require it
* Fix CentOS test mock
* Restore reseting modules list functionality for cleanup
* Move OS fingerprinting and constant mocks to parent class
* Fixes requested in review
* New entrypoint structure and started moving OS constants to override classes
* OS constants move continued, test and linter fixes
* Removed dead code
* Apache compatibility test changest to reflect OS constant restructure
* Test fix
* Requested changes
* Moved Debian specific tests to own test file
* Removed decorator based override class registration in favor of entrypoint dict
* Fix for update_includes for some versions of Augeas
* Take fedora fix into account in tests
* Review fixes
144 lines
5.5 KiB
Python
144 lines
5.5 KiB
Python
""" Distribution specific override class for Debian family (Ubuntu/Debian) """
|
|
import logging
|
|
import os
|
|
import pkg_resources
|
|
|
|
import zope.interface
|
|
|
|
from certbot import errors
|
|
from certbot import interfaces
|
|
from certbot import util
|
|
|
|
from certbot_apache import apache_util
|
|
from certbot_apache import configurator
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
@zope.interface.provider(interfaces.IPluginFactory)
|
|
class DebianConfigurator(configurator.ApacheConfigurator):
|
|
"""Debian specific ApacheConfigurator override class"""
|
|
|
|
OS_DEFAULTS = dict(
|
|
server_root="/etc/apache2",
|
|
vhost_root="/etc/apache2/sites-available",
|
|
vhost_files="*",
|
|
logs_root="/var/log/apache2",
|
|
version_cmd=['apache2ctl', '-v'],
|
|
apache_cmd="apache2ctl",
|
|
restart_cmd=['apache2ctl', 'graceful'],
|
|
conftest_cmd=['apache2ctl', 'configtest'],
|
|
enmod="a2enmod",
|
|
dismod="a2dismod",
|
|
le_vhost_ext="-le-ssl.conf",
|
|
handle_mods=True,
|
|
handle_sites=True,
|
|
challenge_location="/etc/apache2",
|
|
MOD_SSL_CONF_SRC=pkg_resources.resource_filename(
|
|
"certbot_apache", "options-ssl-apache.conf")
|
|
)
|
|
|
|
def enable_site(self, vhost):
|
|
"""Enables an available site, Apache reload required.
|
|
|
|
.. note:: Does not make sure that the site correctly works or that all
|
|
modules are enabled appropriately.
|
|
|
|
:param vhost: vhost to enable
|
|
:type vhost: :class:`~certbot_apache.obj.VirtualHost`
|
|
|
|
:raises .errors.NotSupportedError: If filesystem layout is not
|
|
supported.
|
|
|
|
"""
|
|
if vhost.enabled:
|
|
return
|
|
|
|
enabled_path = ("%s/sites-enabled/%s" %
|
|
(self.parser.root,
|
|
os.path.basename(vhost.filep)))
|
|
if not os.path.isdir(os.path.dirname(enabled_path)):
|
|
# For some reason, sites-enabled / sites-available do not exist
|
|
# Call the parent method
|
|
return super(DebianConfigurator, self).enable_site(vhost)
|
|
self.reverter.register_file_creation(False, enabled_path)
|
|
try:
|
|
os.symlink(vhost.filep, enabled_path)
|
|
except OSError as err:
|
|
if os.path.islink(enabled_path) and os.path.realpath(
|
|
enabled_path) == vhost.filep:
|
|
# Already in shape
|
|
vhost.enabled = True
|
|
return
|
|
else:
|
|
logger.warning(
|
|
"Could not symlink %s to %s, got error: %s", enabled_path,
|
|
vhost.filep, err.strerror)
|
|
errstring = ("Encountered error while trying to enable a " +
|
|
"newly created VirtualHost located at {0} by " +
|
|
"linking to it from {1}")
|
|
raise errors.NotSupportedError(errstring.format(vhost.filep,
|
|
enabled_path))
|
|
vhost.enabled = True
|
|
logger.info("Enabling available site: %s", vhost.filep)
|
|
self.save_notes += "Enabled site %s\n" % vhost.filep
|
|
|
|
def enable_mod(self, mod_name, temp=False):
|
|
# pylint: disable=unused-argument
|
|
"""Enables module in Apache.
|
|
|
|
Both enables and reloads Apache so module is active.
|
|
|
|
:param str mod_name: Name of the module to enable. (e.g. 'ssl')
|
|
:param bool temp: Whether or not this is a temporary action.
|
|
|
|
:raises .errors.NotSupportedError: If the filesystem layout is not
|
|
supported.
|
|
:raises .errors.MisconfigurationError: If a2enmod or a2dismod cannot be
|
|
run.
|
|
|
|
"""
|
|
avail_path = os.path.join(self.parser.root, "mods-available")
|
|
enabled_path = os.path.join(self.parser.root, "mods-enabled")
|
|
if not os.path.isdir(avail_path) or not os.path.isdir(enabled_path):
|
|
raise errors.NotSupportedError(
|
|
"Unsupported directory layout. You may try to enable mod %s "
|
|
"and try again." % mod_name)
|
|
|
|
deps = apache_util.get_mod_deps(mod_name)
|
|
|
|
# Enable all dependencies
|
|
for dep in deps:
|
|
if (dep + "_module") not in self.parser.modules:
|
|
self._enable_mod_debian(dep, temp)
|
|
self.parser.add_mod(dep)
|
|
note = "Enabled dependency of %s module - %s" % (mod_name, dep)
|
|
if not temp:
|
|
self.save_notes += note + os.linesep
|
|
logger.debug(note)
|
|
|
|
# Enable actual module
|
|
self._enable_mod_debian(mod_name, temp)
|
|
self.parser.add_mod(mod_name)
|
|
|
|
if not temp:
|
|
self.save_notes += "Enabled %s module in Apache\n" % mod_name
|
|
logger.info("Enabled Apache %s module", mod_name)
|
|
|
|
# Modules can enable additional config files. Variables may be defined
|
|
# within these new configuration sections.
|
|
# Reload is not necessary as DUMP_RUN_CFG uses latest config.
|
|
self.parser.update_runtime_variables()
|
|
|
|
def _enable_mod_debian(self, mod_name, temp):
|
|
"""Assumes mods-available, mods-enabled layout."""
|
|
# Generate reversal command.
|
|
# Try to be safe here... check that we can probably reverse before
|
|
# applying enmod command
|
|
if not util.exe_exists(self.conf("dismod")):
|
|
raise errors.MisconfigurationError(
|
|
"Unable to find a2dismod, please make sure a2enmod and "
|
|
"a2dismod are configured correctly for certbot.")
|
|
|
|
self.reverter.register_undo_command(
|
|
temp, [self.conf("dismod"), mod_name])
|
|
util.run_script([self.conf("enmod"), mod_name])
|