def config_test(self): # pylint: disable=no-self-use """Check the configuration of Nginx for errors. :raises .errors.MisconfigurationError: If config_test fails """ try: util.run_script([self.conf('ctl'), "-c", self.nginx_conf, "-t"]) except errors.SubprocessError as err: raise errors.MisconfigurationError(str(err))
def _run_undo_commands(self, filepath): # pylint: disable=no-self-use """Run all commands in a file.""" with open(filepath, 'rb') as csvfile: csvreader = csv.reader(csvfile) for command in reversed(list(csvreader)): try: util.run_script(command) except errors.SubprocessError: logger.error( "Unable to run undo command: %s", " ".join(command))
def _run_undo_commands(self, filepath): # pylint: disable=no-self-use """Run all commands in a file.""" with open(filepath, 'rb') as csvfile: csvreader = csv.reader(csvfile) for command in reversed(list(csvreader)): try: util.run_script(command) except errors.SubprocessError: logger.error("Unable to run undo command: %s", " ".join(command))
def _run_undo_commands(self, filepath): # pylint: disable=no-self-use """Run all commands in a file.""" # NOTE: csv module uses native strings. That is, bytes on Python 2 and # unicode on Python 3 with open(filepath, "r") as csvfile: csvreader = csv.reader(csvfile) for command in reversed(list(csvreader)): try: util.run_script(command) except errors.SubprocessError: logger.error("Unable to run undo command: %s", " ".join(command))
def _try_restart_fedora(self): """ Tries to restart httpd using systemctl to generate the self signed keypair. """ try: util.run_script(['systemctl', 'restart', 'httpd']) except errors.SubprocessError as err: raise errors.MisconfigurationError(str(err)) # Finish with actual config check to see if systemctl restart helped super(FedoraConfigurator, self).config_test()
def _run_undo_commands(self, filepath): # pylint: disable=no-self-use """Run all commands in a file.""" # NOTE: csv module uses native strings. That is, bytes on Python 2 and # unicode on Python 3 with open(filepath, 'r') as csvfile: csvreader = csv.reader(csvfile) for command in reversed(list(csvreader)): try: util.run_script(command) except errors.SubprocessError: logger.error("Unable to run undo command: %s", " ".join(command))
def config_test(self): # pylint: disable=no-self-use """Check the configuration of HAProxy for errors. :raises .errors.MisconfigurationError: If config_test fails """ test_cmd = constants.os_constant('conftest_cmd') + \ [self.conf('haproxy_config')] try: util.run_script(test_cmd) except errors.SubprocessError as err: raise errors.MisconfigurationError(str(err))
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.option("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.option("dismod"), "-f", mod_name]) util.run_script([self.option("enmod"), mod_name])
def _run_undo_commands(self, filepath): """Run all commands in a file.""" # NOTE: csv module uses native strings. That is unicode on Python 3 # It is strongly advised to set newline = '' on Python 3 with CSV, # and it fixes problems on Windows. kwargs = {'newline': ''} with open(filepath, 'r', **kwargs) as csvfile: # type: ignore csvreader = csv.reader(csvfile) for command in reversed(list(csvreader)): try: util.run_script(command) except errors.SubprocessError: logger.error("Unable to run undo command: %s", " ".join(command))
def _run_undo_commands(self, filepath): # pylint: disable=no-self-use """Run all commands in a file.""" # NOTE: csv module uses native strings. That is, bytes on Python 2 and # unicode on Python 3 # It is strongly advised to set newline = '' on Python 3 with CSV, # and it fixes problems on Windows. kwargs = {'newline': ''} if sys.version_info[0] > 2 else {} with open(filepath, 'r', **kwargs) as csvfile: # type: ignore csvreader = csv.reader(csvfile) for command in reversed(list(csvreader)): try: util.run_script(command) except errors.SubprocessError: logger.error( "Unable to run undo command: %s", " ".join(command))
def determine_ocsp_server(self, cert_path): """Extract the OCSP server host from a certificate. :param str cert_path: Path to the cert we're checking OCSP for :rtype tuple: :returns: (OCSP server URL or None, OCSP server host or None) """ try: url, _err = util.run_script( ["openssl", "x509", "-in", cert_path, "-noout", "-ocsp_uri"], log=logging.debug) except errors.SubprocessError as e: logger.info("Cannot extract OCSP URI from %s", cert_path) logger.debug("Error was:\n%s", e) return None, None url = url.rstrip() host = url.partition("://")[2].rstrip("/") if host: return url, host else: logger.info("Cannot process OCSP host from URL (%s) in cert at %s", url, cert_path) return None, None
def ocsp_revoked(self, cert_path, chain_path): """Get revoked status for a particular cert version. .. todo:: Make this a non-blocking call :param str cert_path: Path to certificate :param str chain_path: Path to intermediate cert :rtype bool or None: :returns: True if revoked; False if valid or the check failed """ if self.broken: return False url, host = self.determine_ocsp_server(cert_path) if not host: return False # jdkasten thanks "Bulletproof SSL and TLS - Ivan Ristic" for documenting this! cmd = [ "openssl", "ocsp", "-no_nonce", "-issuer", chain_path, "-cert", cert_path, "-url", url, "-CAfile", chain_path, "-verify_other", chain_path, "-trust_other", "-header" ] + self.host_args(host) logger.debug("Querying OCSP for %s", cert_path) logger.debug(" ".join(cmd)) try: output, err = util.run_script(cmd, log=logger.debug) except errors.SubprocessError: logger.info("OCSP check failed for %s (are we offline?)", cert_path) return False return _translate_ocsp_query(cert_path, output, err)
def RequestPKCS12(certpath, datename, webroot, domain): global testcert if 'True' in testcert: params = [ 'certbot', '-n', 'certonly', '--test-cert', '--webroot', '-w', webroot, '-d', domain ] else: params = [ 'certbot', '-n', 'certonly', '--webroot', '-w', webroot, '-d', domain ] get_cert = util.run_script(params) key_pem = open(certpath + 'privkey.pem', 'r').read() cert_pem = open(certpath + 'cert.pem', 'r').read() ca_pem = open(certpath + 'chain.pem', 'r').read() privkey = crypto.load_privatekey(crypto.FILETYPE_PEM, key_pem) cert = crypto.load_certificate(crypto.FILETYPE_PEM, cert_pem) ca = [crypto.load_certificate(crypto.FILETYPE_PEM, ca_pem)] p12 = crypto.PKCS12() p12.set_privatekey(privkey) p12.set_certificate(cert) p12.set_ca_certificates(ca) cert_p12 = p12.export(secret) with open(certpath + datename + '.p12', 'w') as p12file: p12file.write(cert_p12)
def _check_ocsp_openssl_bin(self, cert_path: str, chain_path: str, host: str, url: str, timeout: int) -> bool: # Minimal implementation of proxy selection logic as seen in, e.g., cURL # Some things that won't work, but may well be in use somewhere: # - username and password for proxy authentication # - proxies accepting TLS connections # - proxy exclusion through NO_PROXY env_http_proxy = getenv('http_proxy') env_HTTP_PROXY = getenv('HTTP_PROXY') proxy_host = None if env_http_proxy is not None or env_HTTP_PROXY is not None: proxy_host = env_http_proxy if env_http_proxy is not None else env_HTTP_PROXY if proxy_host is None: url_opts = ["-url", url] else: if proxy_host.startswith('http://'): proxy_host = proxy_host[len('http://'):] url_opts = ["-host", proxy_host, "-path", url] # jdkasten thanks "Bulletproof SSL and TLS - Ivan Ristic" for documenting this! cmd = [ "openssl", "ocsp", "-no_nonce", "-issuer", chain_path, "-cert", cert_path, "-CAfile", chain_path, "-verify_other", chain_path, "-trust_other", "-timeout", str(timeout), "-header" ] + self.host_args(host) + url_opts logger.debug("Querying OCSP for %s", cert_path) logger.debug(" ".join(cmd)) try: output, err = util.run_script(cmd, log=logger.debug) except errors.SubprocessError: logger.info("OCSP check failed for %s (are we offline?)", cert_path) return False return _translate_ocsp_query(cert_path, output, err)
def restart(self): """Runs a config test and restarts HAProxy. :raises .errors.MisconfigurationError: If either the config test or reload fails. """ self.config_test() try: # Read the haproxy-restart command. Per default this is an array # if it is overwritten by the user, it is a string, so we have to # split it over spaces. cmd = self.conf('haproxy-restart') if isinstance(cmd, basestring): cmd = shlex.split(cmd) util.run_script(cmd) except errors.SubprocessError as err: raise errors.MisconfigurationError(str(err))
def _check_ocsp_openssl_bin(self, cert_path, chain_path, host, url): # type: (str, str, str, str) -> bool # jdkasten thanks "Bulletproof SSL and TLS - Ivan Ristic" for documenting this! cmd = [ "openssl", "ocsp", "-no_nonce", "-issuer", chain_path, "-cert", cert_path, "-url", url, "-CAfile", chain_path, "-verify_other", chain_path, "-trust_other", "-header" ] + self.host_args(host) logger.debug("Querying OCSP for %s", cert_path) logger.debug(" ".join(cmd)) try: output, err = util.run_script(cmd, log=logger.debug) except errors.SubprocessError: logger.info("OCSP check failed for %s (are we offline?)", cert_path) return False return _translate_ocsp_query(cert_path, output, err)
def _check_ocsp_openssl_bin(self, cert_path, chain_path, host, url): # type: (str, str, str, str) -> bool # jdkasten thanks "Bulletproof SSL and TLS - Ivan Ristic" for documenting this! cmd = ["openssl", "ocsp", "-no_nonce", "-issuer", chain_path, "-cert", cert_path, "-url", url, "-CAfile", chain_path, "-verify_other", chain_path, "-trust_other", "-header"] + self.host_args(host) logger.debug("Querying OCSP for %s", cert_path) logger.debug(" ".join(cmd)) try: output, err = util.run_script(cmd, log=logger.debug) except errors.SubprocessError: logger.info("OCSP check failed for %s (are we offline?)", cert_path) return False return _translate_ocsp_query(cert_path, output, err)
def determine_ocsp_server(self, cert_path): """Extract the OCSP server host from a certificate. :param str cert_path: Path to the cert we're checking OCSP for :rtype tuple: :returns: (OCSP server URL or None, OCSP server host or None) """ try: url, _err = util.run_script( ["openssl", "x509", "-in", cert_path, "-noout", "-ocsp_uri"], log=logger.debug) except errors.SubprocessError: logger.info("Cannot extract OCSP URI from %s", cert_path) return None, None url = url.rstrip() host = url.partition("://")[2].rstrip("/") if host: return url, host else: logger.info("Cannot process OCSP host from URL (%s) in cert at %s", url, cert_path) return None, None
def ocsp_revoked(self, cert_path, chain_path): """Get revoked status for a particular cert version. .. todo:: Make this a non-blocking call :param str cert_path: Path to certificate :param str chain_path: Path to intermediate cert :rtype bool or None: :returns: True if revoked; False if valid or the check failed """ if self.broken: return False url, host = self.determine_ocsp_server(cert_path) if not host: return False # jdkasten thanks "Bulletproof SSL and TLS - Ivan Ristic" for documenting this! cmd = ["openssl", "ocsp", "-no_nonce", "-issuer", chain_path, "-cert", cert_path, "-url", url, "-CAfile", chain_path, "-verify_other", chain_path, "-trust_other", "-header"] + self.host_args(host) logger.debug("Querying OCSP for %s", cert_path) logger.debug(" ".join(cmd)) try: output, err = util.run_script(cmd, log=logger.debug) except errors.SubprocessError: logger.info("OCSP check failed for %s (are we offline?)", cert_path) return False return _translate_ocsp_query(cert_path, output, err)
def _call(cls, params): from certbot.util import run_script return run_script(params)