certbot_apache.configurator

Apache Configuration based off of Augeas Configurator.

class certbot_apache.configurator.ApacheConfigurator(*args, **kwargs)[source]

Bases: certbot_apache.augeas_configurator.AugeasConfigurator

Apache configurator.

State of Configurator: This code has been been tested and built for Ubuntu 14.04 Apache 2.4 and it works for Ubuntu 12.04 Apache 2.2

Variables:
  • config – Configuration.
  • parser – Handles low level parsing
  • version (tup) – version of Apache
  • vhosts (list) – All vhosts found in the configuration (list of VirtualHost)
  • assoc (dict) – Mapping between domains and vhosts
option(key)[source]

Get a value from options

_prepare_options()[source]

Set the values possibly changed by command line parameters to OS_DEFAULTS constant dictionary

classmethod add_parser_arguments(add)[source]

Add plugin arguments to the CLI argument parser.

NOTE: If some of your flags interact with others, you can use cli.report_config_interaction to register this to ensure values are correctly saved/overridable during renewal.

Parameters:add (callable) – Function that proxies calls to argparse.ArgumentParser.add_argument prepending options with unique plugin name prefix.
mod_ssl_conf

Full absolute path to SSL configuration file.

updated_mod_ssl_conf_digest

Full absolute path to digest of updated SSL configuration file.

prepare()[source]

Prepare the authenticator/installer.

Raises:
  • errors.NoInstallationError – If Apache configs cannot be found
  • errors.MisconfigurationError – If Apache is misconfigured
  • errors.NotSupportedError – If Apache version is not supported
  • errors.PluginError – If there is any other error
_verify_exe_availability(exe)[source]

Checks availability of Apache executable

_check_aug_version()[source]

Checks that we have recent enough version of libaugeas. If augeas version is recent enough, it will support case insensitive regexp matching

get_parser()[source]

Initializes the ApacheParser

_wildcard_domain(domain)[source]

Checks if domain is a wildcard domain

Parameters:domain (str) – Domain to check
Returns:If the domain is wildcard domain
Return type:bool
deploy_cert(domain, cert_path, key_path, chain_path=None, fullchain_path=None)[source]

Deploys certificate to specified virtual host.

Currently tries to find the last directives to deploy the certificate in the VHost associated with the given domain. If it can’t find the directives, it searches the “included” confs. The function verifies that it has located the three directives and finally modifies them to point to the correct destination. After the certificate is installed, the VirtualHost is enabled if it isn’t already.

Todo

Might be nice to remove chain directive if none exists This shouldn’t happen within certbot though

Raises:errors.PluginError – When unable to deploy certificate due to a lack of directives
choose_vhosts(domain, create_if_no_ssl=True)[source]

Finds VirtualHosts that can be used with the provided domain

Parameters:
  • domain (str) – Domain name to match VirtualHosts to
  • create_if_no_ssl (bool) – If found VirtualHost doesn’t have a HTTPS counterpart, should one get created
Returns:

List of VirtualHosts or None

Return type:

list of VirtualHost

_vhosts_for_wildcard(domain)[source]

Get VHost objects for every VirtualHost that the user wants to handle with the wildcard certificate.

_in_wildcard_scope(name, domain)[source]

Helper method for _vhosts_for_wildcard() that makes sure that the domain is in the scope of wildcard domain.

eg. in scope: domain = *.wild.card, name = 1.wild.card not in scope: domain = *.wild.card, name = 1.2.wild.card

_choose_vhosts_wildcard(domain, create_ssl=True)[source]

Prompts user to choose vhosts to install a wildcard certificate for

_deploy_cert(vhost, cert_path, key_path, chain_path, fullchain_path)[source]

Helper function for deploy_cert() that handles the actual deployment this exists because we might want to do multiple deployments per domain originally passed for deploy_cert(). This is especially true with wildcard certificates

choose_vhost(target_name, create_if_no_ssl=True)[source]

Chooses a virtual host based on the given domain name.

If there is no clear virtual host to be selected, the user is prompted with all available choices.

The returned vhost is guaranteed to have TLS enabled unless create_if_no_ssl is set to False, in which case there is no such guarantee and the result is not cached.

Parameters:
  • target_name (str) – domain name
  • create_if_no_ssl (bool) – If found VirtualHost doesn’t have a HTTPS counterpart, should one get created
Returns:

vhost associated with name

Return type:

VirtualHost

Raises:

errors.PluginError – If no vhost is available or chosen

domain_in_names(names, target_name)[source]

Checks if target domain is covered by one or more of the provided names. The target name is matched by wildcard as well as exact match.

Parameters:
  • names (collections.Iterable of str) – server aliases
  • target_name (str) – name to compare with wildcards
Returns:

True if target_name is covered by a wildcard, otherwise, False

Return type:

bool

find_best_http_vhost(target, filter_defaults, port='80')[source]

Returns non-HTTPS vhost objects found from the Apache config

Parameters:
  • target (str) – Domain name of the desired VirtualHost
  • filter_defaults (bool) – whether _default_ vhosts should be included if it is the best match
  • port (str) – port number the vhost should be listening on
Returns:

VirtualHost object that’s the best match for target name

Return type:

obj.VirtualHost or None

_find_best_vhost(target_name, vhosts=None, filter_defaults=True)[source]

Finds the best vhost for a target_name.

This does not upgrade a vhost to HTTPS… it only finds the most appropriate vhost for the given target_name.

Parameters:
  • target_name (str) – domain handled by the desired vhost
  • vhosts (collections.Iterable of VirtualHost) – vhosts to consider
  • filter_defaults (bool) – whether a vhost with a _default_ addr is acceptable
Returns:

VHost or None

_non_default_vhosts(vhosts)[source]

Return all non _default_ only vhosts.

get_all_names()[source]

Returns all names found in the Apache Configuration.

Returns:All ServerNames, ServerAliases, and reverse DNS entries for virtual host addresses
Return type:set
get_name_from_ip(addr)[source]

Returns a reverse dns name if available.

Parameters:addr (Addr) – IP Address
Returns:name or empty string if name cannot be determined
Return type:str
_get_vhost_names(path)[source]

Helper method for getting the ServerName and ServerAlias values from vhost in path

Parameters:path – Path to read ServerName and ServerAliases from
Returns:Tuple including ServerName and list of ServerAlias strings
_add_servernames(host)[source]

Helper function for get_virtual_hosts().

Parameters:host (VirtualHost) – In progress vhost whose names will be added
_create_vhost(path)[source]

Used by get_virtual_hosts to create vhost objects

Parameters:path (str) – Augeas path to virtual host
Returns:newly created vhost
Return type:VirtualHost
get_virtual_hosts()[source]

Returns list of virtual hosts found in the Apache configuration.

Returns:List of VirtualHost objects found in configuration
Return type:list
is_name_vhost(target_addr)[source]

Returns if vhost is a name based vhost

NameVirtualHost was deprecated in Apache 2.4 as all VirtualHosts are now NameVirtualHosts. If version is earlier than 2.4, check if addr has a NameVirtualHost directive in the Apache config

Parameters:target_addr (certbot_apache.obj.Addr) – vhost address
Returns:Success
Return type:bool
add_name_vhost(addr)[source]

Adds NameVirtualHost directive for given address.

Parameters:addr (Addr) – Address that will be added as NameVirtualHost directive
prepare_server_https(port, temp=False)[source]

Prepare the server for HTTPS.

Make sure that the ssl_module is loaded and that the server is appropriately listening on port.

Parameters:port (str) – Port to listen on
ensure_listen(port, https=False)[source]

Make sure that Apache is listening on the port. Checks if the Listen statement for the port already exists, and adds it to the configuration if necessary.

Parameters:
  • port (str) – Port number to check and add Listen for if not in place already
  • https (bool) – If the port will be used for HTTPS
_add_listens_http(listens, listens_orig, port)[source]

Helper method for ensure_listen to figure out which new listen statements need adding for listening HTTP on port

Parameters:
  • listens (set) – Set of all needed Listen statements
  • listens_orig (list) – List of existing listen statements
  • port (string) – Port number we’re adding
_add_listens_https(listens, listens_orig, port)[source]

Helper method for ensure_listen to figure out which new listen statements need adding for listening HTTPS on port

Parameters:
  • listens (set) – Set of all needed Listen statements
  • listens_orig (list) – List of existing listen statements
  • port (string) – Port number we’re adding
_has_port_already(listens, port)[source]

Helper method for prepare_server_https to find out if user already has an active Listen statement for the port we need

Parameters:
  • listens (list) – List of listen variables
  • port (string) – Port in question
prepare_https_modules(temp)[source]

Helper method for prepare_server_https, taking care of enabling needed modules

Parameters:temp (boolean) – If the change is temporary
make_addrs_sni_ready(addrs)[source]

Checks to see if the server is ready for SNI challenges.

Parameters:addrs (Addr) – Addresses to check SNI compatibility
make_vhost_ssl(nonssl_vhost)[source]

Makes an ssl_vhost version of a nonssl_vhost.

Duplicates vhost and adds default ssl options New vhost will reside as (nonssl_vhost.path) + self.option("le_vhost_ext")

Note

This function saves the configuration

Parameters:nonssl_vhost (VirtualHost) – Valid VH that doesn’t have SSLEngine on
Returns:SSL vhost
Return type:VirtualHost
Raises:errors.PluginError – If more than one virtual host is in the file or if plugin is unable to write/read vhost files.
_get_new_vh_path(orig_matches, new_matches)[source]

Helper method for make_vhost_ssl for matching augeas paths. Returns VirtualHost path from new_matches that’s not present in orig_matches.

Paths are normalized, because augeas leaves indices out for paths with only single directive with a similar key

_get_ssl_vhost_path(non_ssl_vh_fp)[source]

Get a file path for SSL vhost, uses user defined path as priority, but if the value is invalid or not defined, will fall back to non-ssl vhost filepath.

Parameters:non_ssl_vh_fp (str) – Filepath of non-SSL vhost
Returns:Filepath for SSL vhost
Return type:str
_sift_rewrite_rule(line)[source]

Decides whether a line should be copied to a SSL vhost.

A canonical example of when sifting a line is required: When the http vhost contains a RewriteRule that unconditionally redirects any request to the https version of the same site. e.g: RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [L,QSA,R=permanent] Copying the above line to the ssl vhost would cause a redirection loop.

Parameters:line (str) – a line extracted from the http vhost.
Returns:True - don’t copy line from http vhost to SSL vhost.
Return type:bool
_copy_create_ssl_vhost_skeleton(vhost, ssl_fp)[source]

Copies over existing Vhost with IfModule mod_ssl.c> skeleton.

Parameters:
  • vhost (obj.VirtualHost) – Original VirtualHost object
  • ssl_fp (str) – Full path where the new ssl_vhost will reside.

A new file is created on the filesystem.

_sift_rewrite_rules(contents)[source]

Helper function for _copy_create_ssl_vhost_skeleton to prepare the new HTTPS VirtualHost contents. Currently disabling the rewrites

_get_vhost_block(vhost)[source]

Helper method to get VirtualHost contents from the original file. This is done with help of augeas span, which returns the span start and end positions

Returns:list of VirtualHost block content lines without closing tag
_remove_closing_vhost_tag(vh_contents)[source]

Removes the closing VirtualHost tag if it exists.

This method modifies vh_contents directly to remove the closing tag. If the closing vhost tag is found, everything on the line after it is also removed. Whether or not this tag is included in the result of span depends on the Augeas version.

Parameters:vh_contents (list) – VirtualHost block contents to check
_has_matching_wildcard(vh_path, target_name)[source]

Is target_name already included in a wildcard in the vhost?

Parameters:
  • vh_path (str) – Augeas path to the vhost
  • target_name (str) – name to compare with wildcards
Returns:

True if there is a wildcard covering target_name in the vhost in vhost_path, otherwise, False

Return type:

bool

_add_name_vhost_if_necessary(vhost)[source]

Add NameVirtualHost Directives if necessary for new vhost.

NameVirtualHosts was a directive in Apache < 2.4 https://httpd.apache.org/docs/2.2/mod/core.html#namevirtualhost

Parameters:vhost (VirtualHost) – New virtual host that was recently created.
find_vhost_by_id(id_str)[source]

Searches through VirtualHosts and tries to match the id in a comment

Parameters:id_str (str) – Id string for matching
Returns:The matched VirtualHost or None
Return type:VirtualHost or None
Raises:errors.PluginError – If no VirtualHost is found
_find_vhost_id(vhost)[source]

Tries to find the unique ID from the VirtualHost comments. This is used for keeping track of VirtualHost directive over time.

Parameters:vhost (VirtualHost) – Virtual host to add the id
Returns:The unique ID or None
Return type:str or None
add_vhost_id(vhost)[source]

Adds an unique ID to the VirtualHost as a comment for mapping back to it on later invocations, as the config file order might have changed. If ID already exists, returns that instead.

Parameters:vhost (VirtualHost) – Virtual host to add or find the id
Returns:The unique ID for vhost
Return type:str or None
supported_enhancements()[source]

Returns currently supported enhancements.

enhance(domain, enhancement, options=None)[source]

Enhance configuration.

Parameters:
  • domain (str) – domain to enhance
  • enhancement (str) – enhancement type defined in ENHANCEMENTS
  • options – options for the enhancement See ENHANCEMENTS documentation for appropriate parameter.
Raises:

errors.PluginError – If Enhancement is not supported, or if there is any other problem with the enhancement.

_autohsts_increase(vhost, id_str, nextstep)[source]

Increase the AutoHSTS max-age value

Parameters:
  • vhost (VirtualHost) – Virtual host object to modify
  • id_str (str) – The unique ID string of VirtualHost
  • nextstep (int) – Next AutoHSTS max-age value index
_autohsts_write(vhost, nextstep_value)[source]

Write the new HSTS max-age value to the VirtualHost file

_autohsts_fetch_state()[source]

Populates the AutoHSTS state from the pluginstorage

_autohsts_save_state()[source]

Saves the state of AutoHSTS object to pluginstorage

_autohsts_vhost_in_lineage(vhost, lineage)[source]

Searches AutoHSTS managed VirtualHosts that belong to the lineage. Matches the private key path.

_enable_ocsp_stapling(ssl_vhost, unused_options)[source]

Enables OCSP Stapling

In OCSP, each client (e.g. browser) would have to query the OCSP Responder to validate that the site certificate was not revoked.

Enabling OCSP Stapling, would allow the web-server to query the OCSP Responder, and staple its response to the offered certificate during TLS. i.e. clients would not have to query the OCSP responder.

OCSP Stapling enablement on Apache implicitly depends on SSLCertificateChainFile being set by other code.

Note

This function saves the configuration

Parameters:
  • ssl_vhost (VirtualHost) – Destination of traffic, an ssl enabled vhost
  • unused_options (Not Available) – Not currently used
Returns:

Success, general_vhost (HTTP vhost)

Return type:

(bool, VirtualHost)

_set_http_header(ssl_vhost, header_substring)[source]

Enables header that is identified by header_substring on ssl_vhost.

If the header identified by header_substring is not already set, a new Header directive is placed in ssl_vhost’s configuration with arguments from: constants.HTTP_HEADER[header_substring]

Note

This function saves the configuration

Parameters:
  • ssl_vhost (VirtualHost) – Destination of traffic, an ssl enabled vhost
  • header_substring – string that uniquely identifies a header. e.g: Strict-Transport-Security, Upgrade-Insecure-Requests.

:type str

Returns:Success, general_vhost (HTTP vhost)
Return type:(bool, VirtualHost)
Raises:errors.PluginError – If no viable HTTP host can be created or set with header header_substring.
_verify_no_matching_http_header(ssl_vhost, header_substring)[source]

Checks to see if an there is an existing Header directive that contains the string header_substring.

Parameters:
  • ssl_vhost – vhost to check
  • header_substring – string that uniquely identifies a header. e.g: Strict-Transport-Security, Upgrade-Insecure-Requests.

:type str

Returns:boolean
Return type:(bool)
:raises errors.PluginEnhancementAlreadyPresent When header
header_substring exists
_enable_redirect(ssl_vhost, unused_options)[source]

Redirect all equivalent HTTP traffic to ssl_vhost.

Todo

This enhancement should be rewritten and will unfortunately require lots of debugging by hand.

Adds Redirect directive to the port 80 equivalent of ssl_vhost First the function attempts to find the vhost with equivalent ip addresses that serves on non-ssl ports The function then adds the directive

Note

This function saves the configuration

Parameters:
  • ssl_vhost (VirtualHost) – Destination of traffic, an ssl enabled vhost
  • unused_options (Not Available) – Not currently used
Raises:

errors.PluginError – If no viable HTTP host can be created or used for the redirect.

_verify_no_certbot_redirect(vhost)[source]

Checks to see if a redirect was already installed by certbot.

Checks to see if virtualhost already contains a rewrite rule that is identical to Certbot’s redirection rewrite rule.

For graceful transition to new rewrite rules for HTTPS redireciton we delete certbot’s old rewrite rules and set the new one instead.

Parameters:vhost (VirtualHost) – vhost to check
Raises:errors.PluginEnhancementAlreadyPresent – When the exact certbot redirection WriteRule exists in virtual host.
_is_rewrite_exists(vhost)[source]

Checks if there exists a RewriteRule directive in vhost

Parameters:vhost (VirtualHost) – vhost to check
Returns:True if a RewriteRule directive exists.
Return type:bool
_is_rewrite_engine_on(vhost)[source]

Checks if a RewriteEngine directive is on

Parameters:vhost (VirtualHost) – vhost to check
_create_redirect_vhost(ssl_vhost)[source]

Creates an http_vhost specifically to redirect for the ssl_vhost.

Parameters:ssl_vhost (VirtualHost) – ssl vhost
Returns:tuple of the form (success, VirtualHost)
Return type:tuple
_get_http_vhost(ssl_vhost)[source]

Find appropriate HTTP vhost for ssl_vhost.

_get_proposed_addrs(vhost, port='80')[source]

Return all addrs of vhost with the port replaced with the specified.

Parameters:
  • ssl_vhost (obj.VirtualHost) – Original Vhost
  • port (str) – Desired port for new addresses
Returns:

set of Addr

enable_site(vhost)[source]

Enables an available site, Apache reload required.

Note

Does not make sure that the site correctly works or that all modules are enabled appropriately.

Note

The distribution specific override replaces functionality of this method where available.

Parameters:vhost (VirtualHost) – vhost to enable
Raises:errors.NotSupportedError – If filesystem layout is not supported.
enable_mod(mod_name, temp=False)[source]

Enables module in Apache.

Both enables and reloads Apache so module is active.

Parameters:
  • mod_name (str) – Name of the module to enable. (e.g. ‘ssl’)
  • temp (bool) – Whether or not this is a temporary action.

Note

The distribution specific override replaces functionality of this method where available.

Raises:errors.MisconfigurationError – We cannot enable modules in generic fashion.
restart()[source]

Runs a config test and reloads the Apache server.

Raises:errors.MisconfigurationError – If either the config test or reload fails.
_reload()[source]

Reloads the Apache server.

Raises:errors.MisconfigurationError – If reload fails
config_test()[source]

Check the configuration of Apache for errors.

Raises:errors.MisconfigurationError – If config_test fails
get_version()[source]

Return version of Apache Server.

Version is returned as tuple. (ie. 2.4.7 = (2, 4, 7))

Returns:version
Return type:tuple
Raises:PluginError – if unable to find Apache version
more_info()[source]

Human-readable string to help understand the module

get_chall_pref(unused_domain)[source]

Return list of challenge preferences.

perform(achalls)[source]

Perform the configuration related challenge.

This function currently assumes all challenges will be fulfilled. If this turns out not to be the case in the future. Cleanup and outstanding challenges will have to be designed better.

cleanup(achalls)[source]

Revert all challenges.

install_ssl_options_conf(options_ssl, options_ssl_digest)[source]

Copy Certbot’s SSL options file into the system’s config dir if required.

enable_autohsts(_unused_lineage, domains)[source]

Enable the AutoHSTS enhancement for defined domains

Parameters:
  • _unused_lineage (certbot.storage.RenewableCert) – Certificate lineage object, unused
  • domains (str) – List of domains in certificate to enhance
_enable_autohsts_domain(ssl_vhost)[source]

Do the initial AutoHSTS deployment to a vhost

Parameters:ssl_vhost (VirtualHost or None) – The VirtualHost object to deploy the AutoHSTS
Raises:errors.PluginEnhancementAlreadyPresent – When already enhanced
update_autohsts(_unused_domain)[source]

Increase the AutoHSTS values of VirtualHosts that the user has enabled this enhancement for.

Parameters:_unused_domain (Not Available) – Not currently used
deploy_autohsts(lineage)[source]

Checks if autohsts vhost has reached maximum auto-increased value and changes the HSTS max-age to a high value.

Parameters:lineage (certbot.storage.RenewableCert) – Certificate lineage object