response
stringlengths 1
33.1k
| instruction
stringlengths 22
582k
|
---|---|
Helper to wait for a specified or well-known redis key to contain a string. | def await_redis_list_message_length(expected_length, redis_key="redis-group-ids", timeout=TIMEOUT):
"""
Helper to wait for a specified or well-known redis key to contain a string.
"""
sleep(1)
redis_connection = get_redis_connection()
check_interval = 0.1
check_max = int(timeout / check_interval)
for i in range(check_max + 1):
length = redis_connection.llen(redis_key)
if length == expected_length:
break
sleep(check_interval)
else:
raise TimeoutError(f'{redis_key!r} has length of {length}, but expected to be of length {expected_length}')
sleep(min(1, timeout))
assert redis_connection.llen(redis_key) == expected_length |
Helper to wait for a specified or well-known redis key to count to a value. | def await_redis_count(expected_count, redis_key="redis-count", timeout=TIMEOUT):
"""
Helper to wait for a specified or well-known redis key to count to a value.
"""
redis_connection = get_redis_connection()
check_interval = 0.1
check_max = int(timeout / check_interval)
for i in range(check_max + 1):
maybe_count = redis_connection.get(redis_key)
# It's either `None` or a base-10 integer
if maybe_count is not None:
count = int(maybe_count)
if count == expected_count:
break
elif i >= check_max:
assert count == expected_count
# try again later
sleep(check_interval)
else:
raise TimeoutError(f"{redis_key!r} was never incremented")
# There should be no more increments - block momentarily
sleep(min(1, timeout))
assert int(redis_connection.get(redis_key)) == expected_count |
run a worker and return its stderr
:param name: the name of the worker
:param env: the environment to run the worker in
worker must be running in other process because of avoiding conflict. | def get_worker_error_messages(name, env):
"""run a worker and return its stderr
:param name: the name of the worker
:param env: the environment to run the worker in
worker must be running in other process because of avoiding conflict."""
worker = subprocess.Popen(
[
"celery",
"--config",
"t.integration.test_serialization_config",
"worker",
"-c",
"2",
"-n",
f"{name}@%%h",
],
stderr=subprocess.PIPE,
stdout=subprocess.PIPE,
env=env,
)
worker.terminate()
err = worker.stderr.read().decode("utf-8")
return err |
Set multiprocessing start method to 'fork' if not on Linux. | def set_multiprocessing_start_method():
"""Set multiprocessing start method to 'fork' if not on Linux."""
if platform.system() != 'Linux':
try:
set_start_method('fork')
except RuntimeError:
# The method is already set
pass |
Single producer helper function | def _producer(j):
"""Single producer helper function"""
results = []
for i in range(20):
results.append([i + j, add.delay(i, j)])
for expected, result in results:
value = result.get(timeout=10)
assert value == expected
assert result.status == 'SUCCESS'
assert result.ready() is True
assert result.successful() is True
return j |
Use all of the integration and smoke suites tasks in the smoke tests workers. | def default_worker_tasks(default_worker_tasks: set) -> set:
"""Use all of the integration and smoke suites tasks in the smoke tests workers."""
from t.integration import tasks as integration_tests_tasks
from t.smoke import tasks as smoke_tests_tasks
default_worker_tasks.add(integration_tests_tasks)
default_worker_tasks.add(smoke_tests_tasks)
return default_worker_tasks |
Configure the Redis test container to be used by the integration tests tasks. | def set_redis_test_container(redis_test_container: RedisContainer):
"""Configure the Redis test container to be used by the integration tests tasks."""
os.environ["REDIS_PORT"] = str(redis_test_container.port) |
Forceful termination. | def self_termination_sigkill():
"""Forceful termination."""
os.kill(os.getpid(), SIGKILL) |
Triggers a system exit to simulate a critical stop of the Celery worker. | def self_termination_system_exit():
"""Triggers a system exit to simulate a critical stop of the Celery worker."""
sys.exit(1) |
Delays the execution to simulate a task timeout. | def self_termination_delay_timeout():
"""Delays the execution to simulate a task timeout."""
sleep(4) |
Continuously allocates memory to simulate memory exhaustion. | def self_termination_exhaust_memory():
"""Continuously allocates memory to simulate memory exhaustion."""
mem = []
while True:
mem.append(" " * 10**6) |
Returns a matrix of hybrid worker clusters
Each item in the matrix is a list of workers to be used in the cluster
and each cluster will be tested separately (with parallel support) | def get_hybrid_clusters_matrix() -> list[list[str]]:
"""Returns a matrix of hybrid worker clusters
Each item in the matrix is a list of workers to be used in the cluster
and each cluster will be tested separately (with parallel support)
"""
return [
# Dev worker only
["celery_setup_worker"],
# Legacy (Celery 4) worker only
["celery_legacy_worker"],
# Both dev and legacy workers
["celery_setup_worker", "celery_legacy_worker"],
# Dev worker and last official Celery release worker
["celery_setup_worker", "celery_latest_worker"],
# Dev worker and legacy worker and last official Celery release worker
["celery_setup_worker", "celery_latest_worker", "celery_legacy_worker"],
] |
Creates a pytest-celery worker node from the worker container. | def celery_alt_dev_worker(
alt_dev_worker_container: AltSmokeWorkerContainer,
celery_setup_app: Celery,
) -> CeleryTestWorker:
"""Creates a pytest-celery worker node from the worker container."""
worker = CeleryTestWorker(alt_dev_worker_container, app=celery_setup_app)
yield worker
worker.teardown() |
Replace the default pytest-celery worker container with the smoke tests worker container.
This will allow the default fixtures of pytest-celery to use the custom worker
configuration using the vendor class. | def default_worker_container_cls() -> Type[CeleryWorkerContainer]:
"""Replace the default pytest-celery worker container with the smoke tests worker container.
This will allow the default fixtures of pytest-celery to use the custom worker
configuration using the vendor class.
"""
return SmokeWorkerContainer |
Replace the default pytest-celery worker container with the smoke tests worker container.
This will allow the default fixtures of pytest-celery to use the custom worker
configuration using the vendor class. | def default_worker_container_session_cls() -> Type[CeleryWorkerContainer]:
"""Replace the default pytest-celery worker container with the smoke tests worker container.
This will allow the default fixtures of pytest-celery to use the custom worker
configuration using the vendor class.
"""
return SmokeWorkerContainer |
Creates a pytest-celery worker node from the worker container. | def celery_latest_worker(
celery_latest_worker_container: CeleryLatestWorkerContainer,
celery_setup_app: Celery,
) -> CeleryTestWorker:
"""Creates a pytest-celery worker node from the worker container."""
worker = CeleryTestWorker(celery_latest_worker_container, app=celery_setup_app)
yield worker
worker.teardown() |
Creates a pytest-celery worker node from the worker container. | def celery_other_dev_worker(
other_dev_worker_container: OtherSmokeWorkerContainer,
celery_setup_app: Celery,
) -> CeleryTestWorker:
"""Creates a pytest-celery worker node from the worker container."""
worker = CeleryTestWorker(other_dev_worker_container, app=celery_setup_app)
yield worker
worker.teardown() |
Fixture that resets the internal state of the cache result backend. | def reset_cache_backend_state(celery_app):
"""Fixture that resets the internal state of the cache result backend."""
yield
backend = celery_app.__dict__.get('backend')
if backend is not None:
if isinstance(backend, CacheBackend):
if isinstance(backend.client, DummyClient):
backend.client.cache.clear()
backend._cache.clear() |
Context that verifies signal is called before exiting. | def assert_signal_called(signal, **expected):
"""Context that verifies signal is called before exiting."""
handler = Mock()
def on_call(**kwargs):
return handler(**kwargs)
signal.connect(on_call)
try:
yield handler
finally:
signal.disconnect(on_call)
handler.assert_called_with(signal=signal, **expected) |
Mock sleep method in patched module to do nothing.
Example:
>>> import time
>>> @pytest.mark.sleepdeprived_patched_module(time)
>>> def test_foo(self, sleepdeprived):
>>> pass | def sleepdeprived(request):
"""Mock sleep method in patched module to do nothing.
Example:
>>> import time
>>> @pytest.mark.sleepdeprived_patched_module(time)
>>> def test_foo(self, sleepdeprived):
>>> pass
"""
module = request.node.get_closest_marker(
"sleepdeprived_patched_module").args[0]
old_sleep, module.sleep = module.sleep, noop
try:
yield
finally:
module.sleep = old_sleep |
Ban some modules from being importable inside the context
For example::
>>> @pytest.mark.masked_modules('gevent.monkey')
>>> def test_foo(self, mask_modules):
... try:
... import sys
... except ImportError:
... print('sys not found')
sys not found | def mask_modules(request):
"""Ban some modules from being importable inside the context
For example::
>>> @pytest.mark.masked_modules('gevent.monkey')
>>> def test_foo(self, mask_modules):
... try:
... import sys
... except ImportError:
... print('sys not found')
sys not found
"""
realimport = builtins.__import__
modnames = request.node.get_closest_marker("masked_modules").args
def myimp(name, *args, **kwargs):
if name in modnames:
raise ImportError('No module named %s' % name)
else:
return realimport(name, *args, **kwargs)
builtins.__import__ = myimp
try:
yield
finally:
builtins.__import__ = realimport |
Mock environment variable value.
Example::
>>> @pytest.mark.patched_environ('DJANGO_SETTINGS_MODULE', 'proj.settings')
>>> def test_other_settings(self, environ):
... ... | def environ(request):
"""Mock environment variable value.
Example::
>>> @pytest.mark.patched_environ('DJANGO_SETTINGS_MODULE', 'proj.settings')
>>> def test_other_settings(self, environ):
... ...
"""
env_name, env_value = request.node.get_closest_marker("patched_environ").args
prev_val = os.environ.get(env_name, SENTINEL)
os.environ[env_name] = env_value
try:
yield
finally:
if prev_val is SENTINEL:
os.environ.pop(env_name, None)
else:
os.environ[env_name] = prev_val |
Mock module value, given a module, attribute name and value.
Example::
>>> replace_module_value(module, 'CONSTANT', 3.03) | def replace_module_value(module, name, value=None):
"""Mock module value, given a module, attribute name and value.
Example::
>>> replace_module_value(module, 'CONSTANT', 3.03)
"""
has_prev = hasattr(module, name)
prev = getattr(module, name, None)
if value:
setattr(module, name, value)
else:
try:
delattr(module, name)
except AttributeError:
pass
try:
yield
finally:
if prev is not None:
setattr(module, name, prev)
if not has_prev:
try:
delattr(module, name)
except AttributeError:
pass |
Mock :data:`platform.python_implementation`
Example::
>>> with platform_pyimp('PyPy'):
... ... | def platform_pyimp(value=None):
"""Mock :data:`platform.python_implementation`
Example::
>>> with platform_pyimp('PyPy'):
... ...
"""
yield from replace_module_value(platform, 'python_implementation', value) |
Mock :data:`sys.platform`
Example::
>>> mock.sys_platform('darwin'):
... ... | def sys_platform(value=None):
"""Mock :data:`sys.platform`
Example::
>>> mock.sys_platform('darwin'):
... ...
"""
prev, sys.platform = sys.platform, value
try:
yield
finally:
sys.platform = prev |
Mock :data:`sys.pypy_version_info`
Example::
>>> with pypy_version((3, 6, 1)):
... ... | def pypy_version(value=None):
"""Mock :data:`sys.pypy_version_info`
Example::
>>> with pypy_version((3, 6, 1)):
... ...
"""
yield from replace_module_value(sys, 'pypy_version_info', value) |
Restore root logger handlers after test returns.
Example::
>>> with restore_logging_context_manager():
... setup_logging() | def restore_logging_context_manager():
"""Restore root logger handlers after test returns.
Example::
>>> with restore_logging_context_manager():
... setup_logging()
"""
yield from _restore_logging() |
Restore root logger handlers after test returns.
Example::
>>> def test_foo(self, restore_logging):
... setup_logging() | def restore_logging(request):
"""Restore root logger handlers after test returns.
Example::
>>> def test_foo(self, restore_logging):
... setup_logging()
"""
yield from _restore_logging() |
Mock one or modules such that every attribute is a :class:`Mock`. | def module(request):
"""Mock one or modules such that every attribute is a :class:`Mock`."""
yield from _module(*request.node.get_closest_marker("patched_module").args) |
Mock one or modules such that every attribute is a :class:`Mock`. | def module_context_manager(*names):
"""Mock one or modules such that every attribute is a :class:`Mock`."""
yield from _module(*names) |
Monkeypath.setattr shortcut.
Example:
.. code-block:: python
>>> def test_foo(patching):
>>> # execv value here will be mock.MagicMock by default.
>>> execv = patching('os.execv')
>>> patching('sys.platform', 'darwin') # set concrete value
>>> patching.setenv('DJANGO_SETTINGS_MODULE', 'x.settings')
>>> # val will be of type mock.MagicMock by default
>>> val = patching.setitem('path.to.dict', 'KEY') | def patching(monkeypatch, request):
"""Monkeypath.setattr shortcut.
Example:
.. code-block:: python
>>> def test_foo(patching):
>>> # execv value here will be mock.MagicMock by default.
>>> execv = patching('os.execv')
>>> patching('sys.platform', 'darwin') # set concrete value
>>> patching.setenv('DJANGO_SETTINGS_MODULE', 'x.settings')
>>> # val will be of type mock.MagicMock by default
>>> val = patching.setitem('path.to.dict', 'KEY')
"""
return _patching(monkeypatch, request) |
Override `sys.stdout` and `sys.stderr` with `StringIO`
instances.
>>> with conftest.stdouts() as (stdout, stderr):
... something()
... self.assertIn('foo', stdout.getvalue()) | def stdouts():
"""Override `sys.stdout` and `sys.stderr` with `StringIO`
instances.
>>> with conftest.stdouts() as (stdout, stderr):
... something()
... self.assertIn('foo', stdout.getvalue())
"""
prev_out, prev_err = sys.stdout, sys.stderr
prev_rout, prev_rerr = sys.__stdout__, sys.__stderr__
mystdout, mystderr = WhateverIO(), WhateverIO()
sys.stdout = sys.__stdout__ = mystdout
sys.stderr = sys.__stderr__ = mystderr
try:
yield mystdout, mystderr
finally:
sys.stdout = prev_out
sys.stderr = prev_err
sys.__stdout__ = prev_rout
sys.__stderr__ = prev_rerr |
Remove modules from :data:`sys.modules` by name,
and reset back again when the test/context returns.
Example::
>>> with conftest.reset_modules('celery.result', 'celery.app.base'):
... pass | def reset_modules(*modules):
"""Remove modules from :data:`sys.modules` by name,
and reset back again when the test/context returns.
Example::
>>> with conftest.reset_modules('celery.result', 'celery.app.base'):
... pass
"""
prev = {
k: sys.modules.pop(k) for k in modules if k in sys.modules
}
try:
for k in modules:
reload(import_module(k))
yield
finally:
sys.modules.update(prev) |
Wrap :class:`logging.Logger` with a StringIO() handler.
yields a StringIO handle.
Example::
>>> with conftest.wrap_logger(logger, loglevel=logging.DEBUG) as sio:
... ...
... sio.getvalue() | def wrap_logger(logger, loglevel=logging.ERROR):
"""Wrap :class:`logging.Logger` with a StringIO() handler.
yields a StringIO handle.
Example::
>>> with conftest.wrap_logger(logger, loglevel=logging.DEBUG) as sio:
... ...
... sio.getvalue()
"""
old_handlers = get_logger_handlers(logger)
sio = WhateverIO()
siohandler = logging.StreamHandler(sio)
logger.handlers = [siohandler]
try:
yield sio
finally:
logger.handlers = old_handlers |
Patch builtins.open so that it returns StringIO object.
:param side_effect: Additional side effect for when the open context
is entered.
Example::
>>> with mock.open(io.BytesIO) as open_fh:
... something_opening_and_writing_bytes_to_a_file()
... self.assertIn(b'foo', open_fh.getvalue()) | def open(side_effect=None):
"""Patch builtins.open so that it returns StringIO object.
:param side_effect: Additional side effect for when the open context
is entered.
Example::
>>> with mock.open(io.BytesIO) as open_fh:
... something_opening_and_writing_bytes_to_a_file()
... self.assertIn(b'foo', open_fh.getvalue())
"""
with patch('builtins.open') as open_:
with _mock_context(open_) as context:
if side_effect is not None:
context.__enter__.side_effect = side_effect
val = context.__enter__.return_value = WhateverIO()
val.__exit__ = Mock()
yield val |
Patch one or more modules to ensure they exist.
A module name with multiple paths (e.g. gevent.monkey) will
ensure all parent modules are also patched (``gevent`` +
``gevent.monkey``).
Example::
>>> with conftest.module_exists('gevent.monkey'):
... gevent.monkey.patch_all = Mock(name='patch_all')
... ... | def module_exists(*modules):
"""Patch one or more modules to ensure they exist.
A module name with multiple paths (e.g. gevent.monkey) will
ensure all parent modules are also patched (``gevent`` +
``gevent.monkey``).
Example::
>>> with conftest.module_exists('gevent.monkey'):
... gevent.monkey.patch_all = Mock(name='patch_all')
... ...
"""
gen = []
old_modules = []
for module in modules:
if isinstance(module, str):
module = types.ModuleType(module)
gen.append(module)
if module.__name__ in sys.modules:
old_modules.append(sys.modules[module.__name__])
sys.modules[module.__name__] = module
name = module.__name__
if '.' in name:
parent, _, attr = name.rpartition('.')
setattr(sys.modules[parent], attr, module)
try:
yield
finally:
for module in gen:
sys.modules.pop(module.__name__, None)
for module in old_modules:
sys.modules[module.__name__] = module |
Helper embedded worker for testing.
It's based on a :func:`celery.contrib.testing.worker.start_worker`,
but doesn't modify logging settings and additionally shutdown
worker pool. | def embed_worker(app,
concurrency=1,
pool='threading', **kwargs):
"""
Helper embedded worker for testing.
It's based on a :func:`celery.contrib.testing.worker.start_worker`,
but doesn't modify logging settings and additionally shutdown
worker pool.
"""
# prepare application for worker
app.finalize()
app.set_current()
worker = contrib_embed_worker.TestWorkController(
app=app,
concurrency=concurrency,
hostname=anon_nodename(),
pool=pool,
# not allowed to override TestWorkController.on_consumer_ready
ready_callback=None,
without_heartbeat=kwargs.pop("without_heartbeat", True),
without_mingle=True,
without_gossip=True,
**kwargs
)
t = threading.Thread(target=worker.start, daemon=True)
t.start()
worker.ensure_started()
yield worker
worker.stop()
t.join(10.0)
if t.is_alive():
raise RuntimeError(
"Worker thread failed to exit within the allocated timeout. "
"Consider raising `shutdown_timeout` if your tasks take longer "
"to execute."
) |
Return a factory that creates MongoBackend instance with given serializer, including BSON. | def mongo_backend_factory(app):
"""Return a factory that creates MongoBackend instance with given serializer, including BSON."""
def create_mongo_backend(serializer):
# NOTE: `bson` is a only mongodb-specific type and can be set only directly on MongoBackend instance.
if serializer == "bson":
beckend = MongoBackend(app=app)
beckend.serializer = serializer
else:
app.conf.accept_content = ['json', 'pickle', 'msgpack', 'yaml']
app.conf.result_serializer = serializer
beckend = MongoBackend(app=app)
return beckend
yield create_mongo_backend |
Ask the workers to reply with a and b. | def custom_control_cmd(state, a, b):
"""Ask the workers to reply with a and b."""
return {'ok': f'Received {a} and {b}'} |
Ask the workers to reply with x. | def custom_inspect_cmd(state, x):
"""Ask the workers to reply with x."""
return {'ok': f'Received {x}'} |
Verify that using the 'celery' marker does not result in a warning | def test_pytest_celery_marker_registration(testdir):
"""Verify that using the 'celery' marker does not result in a warning"""
testdir.plugins.append("celery")
testdir.makepyfile(
"""
import pytest
@pytest.mark.celery(foo="bar")
def test_noop():
pass
"""
)
result = testdir.runpytest('-q')
with pytest.raises((ValueError, Failed)):
result.stdout.fnmatch_lines_random(
"*PytestUnknownMarkWarning: Unknown pytest.mark.celery*"
) |
Task.
This is a sample Task. | def bar():
"""Task.
This is a sample Task.
""" |
Shared Task.
This is a sample Shared Task. | def baz():
"""Shared Task.
This is a sample Shared Task.
""" |
This task is in a different module! | def plugh():
"""This task is in a different module!""" |
Quick task event. | def QTEV(type, uuid, hostname, clock, name=None, timestamp=None):
"""Quick task event."""
return Event(f'task-{type}', uuid=uuid, hostname=hostname,
clock=clock, name=name, timestamp=timestamp or time()) |
Pylint hook to auto-register this linter | def register(linter):
"""Pylint hook to auto-register this linter"""
linter.register_checker(ForbidStandardOsModule(linter)) |
Probe SNI server for SSL certificate.
:param bytes name: Byte string to send as the server name in the
client hello message.
:param bytes host: Host to connect to.
:param int port: Port to connect to.
:param int timeout: Timeout in seconds.
:param method: See `OpenSSL.SSL.Context` for allowed values.
:param tuple source_address: Enables multi-path probing (selection
of source interface). See `socket.creation_connection` for more
info. Available only in Python 2.7+.
:param alpn_protocols: Protocols to request using ALPN.
:type alpn_protocols: `Sequence` of `bytes`
:raises acme.errors.Error: In case of any problems.
:returns: SSL certificate presented by the server.
:rtype: OpenSSL.crypto.X509 | def probe_sni(name: bytes, host: bytes, port: int = 443, timeout: int = 300, # pylint: disable=too-many-arguments
method: int = _DEFAULT_SSL_METHOD, source_address: Tuple[str, int] = ('', 0),
alpn_protocols: Optional[Sequence[bytes]] = None) -> crypto.X509:
"""Probe SNI server for SSL certificate.
:param bytes name: Byte string to send as the server name in the
client hello message.
:param bytes host: Host to connect to.
:param int port: Port to connect to.
:param int timeout: Timeout in seconds.
:param method: See `OpenSSL.SSL.Context` for allowed values.
:param tuple source_address: Enables multi-path probing (selection
of source interface). See `socket.creation_connection` for more
info. Available only in Python 2.7+.
:param alpn_protocols: Protocols to request using ALPN.
:type alpn_protocols: `Sequence` of `bytes`
:raises acme.errors.Error: In case of any problems.
:returns: SSL certificate presented by the server.
:rtype: OpenSSL.crypto.X509
"""
context = SSL.Context(method)
context.set_timeout(timeout)
socket_kwargs = {'source_address': source_address}
try:
logger.debug(
"Attempting to connect to %s:%d%s.", host, port,
" from {0}:{1}".format(
source_address[0],
source_address[1]
) if any(source_address) else ""
)
socket_tuple: Tuple[bytes, int] = (host, port)
sock = socket.create_connection(socket_tuple, **socket_kwargs) # type: ignore[arg-type]
except socket.error as error:
raise errors.Error(error)
with contextlib.closing(sock) as client:
client_ssl = SSL.Connection(context, client)
client_ssl.set_connect_state()
client_ssl.set_tlsext_host_name(name) # pyOpenSSL>=0.13
if alpn_protocols is not None:
client_ssl.set_alpn_protos(alpn_protocols)
try:
client_ssl.do_handshake()
client_ssl.shutdown()
except SSL.Error as error:
raise errors.Error(error)
cert = client_ssl.get_peer_certificate()
assert cert # Appease mypy. We would have crashed out by now if there was no certificate.
return cert |
Generate a CSR containing domains or IPs as subjectAltNames.
:param buffer private_key_pem: Private key, in PEM PKCS#8 format.
:param list domains: List of DNS names to include in subjectAltNames of CSR.
:param bool must_staple: Whether to include the TLS Feature extension (aka
OCSP Must Staple: https://tools.ietf.org/html/rfc7633).
:param list ipaddrs: List of IPaddress(type ipaddress.IPv4Address or ipaddress.IPv6Address)
names to include in subbjectAltNames of CSR.
params ordered this way for backward competablity when called by positional argument.
:returns: buffer PEM-encoded Certificate Signing Request. | def make_csr(private_key_pem: bytes, domains: Optional[Union[Set[str], List[str]]] = None,
must_staple: bool = False,
ipaddrs: Optional[List[Union[ipaddress.IPv4Address, ipaddress.IPv6Address]]] = None
) -> bytes:
"""Generate a CSR containing domains or IPs as subjectAltNames.
:param buffer private_key_pem: Private key, in PEM PKCS#8 format.
:param list domains: List of DNS names to include in subjectAltNames of CSR.
:param bool must_staple: Whether to include the TLS Feature extension (aka
OCSP Must Staple: https://tools.ietf.org/html/rfc7633).
:param list ipaddrs: List of IPaddress(type ipaddress.IPv4Address or ipaddress.IPv6Address)
names to include in subbjectAltNames of CSR.
params ordered this way for backward competablity when called by positional argument.
:returns: buffer PEM-encoded Certificate Signing Request.
"""
private_key = crypto.load_privatekey(
crypto.FILETYPE_PEM, private_key_pem)
csr = crypto.X509Req()
sanlist = []
# if domain or ip list not supplied make it empty list so it's easier to iterate
if domains is None:
domains = []
if ipaddrs is None:
ipaddrs = []
if len(domains)+len(ipaddrs) == 0:
raise ValueError("At least one of domains or ipaddrs parameter need to be not empty")
for address in domains:
sanlist.append('DNS:' + address)
for ips in ipaddrs:
sanlist.append('IP:' + ips.exploded)
# make sure its ascii encoded
san_string = ', '.join(sanlist).encode('ascii')
# for IP san it's actually need to be octet-string,
# but somewhere downsteam thankfully handle it for us
extensions = [
crypto.X509Extension(
b'subjectAltName',
critical=False,
value=san_string
),
]
if must_staple:
extensions.append(crypto.X509Extension(
b"1.3.6.1.5.5.7.1.24",
critical=False,
value=b"DER:30:03:02:01:05"))
csr.add_extensions(extensions)
csr.set_pubkey(private_key)
# RFC 2986 Section 4.1 only defines version 0
csr.set_version(0)
csr.sign(private_key, 'sha256')
return crypto.dump_certificate_request(
crypto.FILETYPE_PEM, csr) |
Get Subject Alternative Names from certificate or CSR using pyOpenSSL.
.. todo:: Implement directly in PyOpenSSL!
.. note:: Although this is `acme` internal API, it is used by
`letsencrypt`.
:param cert_or_req: Certificate or CSR.
:type cert_or_req: `OpenSSL.crypto.X509` or `OpenSSL.crypto.X509Req`.
:returns: A list of Subject Alternative Names that is DNS.
:rtype: `list` of `str` | def _pyopenssl_cert_or_req_san(cert_or_req: Union[crypto.X509, crypto.X509Req]) -> List[str]:
"""Get Subject Alternative Names from certificate or CSR using pyOpenSSL.
.. todo:: Implement directly in PyOpenSSL!
.. note:: Although this is `acme` internal API, it is used by
`letsencrypt`.
:param cert_or_req: Certificate or CSR.
:type cert_or_req: `OpenSSL.crypto.X509` or `OpenSSL.crypto.X509Req`.
:returns: A list of Subject Alternative Names that is DNS.
:rtype: `list` of `str`
"""
# This function finds SANs with dns name
# constants based on PyOpenSSL certificate/CSR text dump
part_separator = ":"
prefix = "DNS" + part_separator
sans_parts = _pyopenssl_extract_san_list_raw(cert_or_req)
return [part.split(part_separator)[1]
for part in sans_parts if part.startswith(prefix)] |
Get Subject Alternative Names IPs from certificate or CSR using pyOpenSSL.
:param cert_or_req: Certificate or CSR.
:type cert_or_req: `OpenSSL.crypto.X509` or `OpenSSL.crypto.X509Req`.
:returns: A list of Subject Alternative Names that are IP Addresses.
:rtype: `list` of `str`. note that this returns as string, not IPaddress object | def _pyopenssl_cert_or_req_san_ip(cert_or_req: Union[crypto.X509, crypto.X509Req]) -> List[str]:
"""Get Subject Alternative Names IPs from certificate or CSR using pyOpenSSL.
:param cert_or_req: Certificate or CSR.
:type cert_or_req: `OpenSSL.crypto.X509` or `OpenSSL.crypto.X509Req`.
:returns: A list of Subject Alternative Names that are IP Addresses.
:rtype: `list` of `str`. note that this returns as string, not IPaddress object
"""
# constants based on PyOpenSSL certificate/CSR text dump
part_separator = ":"
prefix = "IP Address" + part_separator
sans_parts = _pyopenssl_extract_san_list_raw(cert_or_req)
return [part[len(prefix):] for part in sans_parts if part.startswith(prefix)] |
Get raw SAN string from cert or csr, parse it as UTF-8 and return.
:param cert_or_req: Certificate or CSR.
:type cert_or_req: `OpenSSL.crypto.X509` or `OpenSSL.crypto.X509Req`.
:returns: raw san strings, parsed byte as utf-8
:rtype: `list` of `str` | def _pyopenssl_extract_san_list_raw(cert_or_req: Union[crypto.X509, crypto.X509Req]) -> List[str]:
"""Get raw SAN string from cert or csr, parse it as UTF-8 and return.
:param cert_or_req: Certificate or CSR.
:type cert_or_req: `OpenSSL.crypto.X509` or `OpenSSL.crypto.X509Req`.
:returns: raw san strings, parsed byte as utf-8
:rtype: `list` of `str`
"""
# This function finds SANs by dumping the certificate/CSR to text and
# searching for "X509v3 Subject Alternative Name" in the text. This method
# is used to because in PyOpenSSL version <0.17 `_subjectAltNameString` methods are
# not able to Parse IP Addresses in subjectAltName string.
if isinstance(cert_or_req, crypto.X509):
# pylint: disable=line-too-long
text = crypto.dump_certificate(crypto.FILETYPE_TEXT, cert_or_req).decode('utf-8')
else:
text = crypto.dump_certificate_request(crypto.FILETYPE_TEXT, cert_or_req).decode('utf-8')
# WARNING: this function does not support multiple SANs extensions.
# Multiple X509v3 extensions of the same type is disallowed by RFC 5280.
raw_san = re.search(r"X509v3 Subject Alternative Name:(?: critical)?\s*(.*)", text)
parts_separator = ", "
# WARNING: this function assumes that no SAN can include
# parts_separator, hence the split!
sans_parts = [] if raw_san is None else raw_san.group(1).split(parts_separator)
return sans_parts |
Generate new self-signed certificate.
:type domains: `list` of `str`
:param OpenSSL.crypto.PKey key:
:param bool force_san:
:param extensions: List of additional extensions to include in the cert.
:type extensions: `list` of `OpenSSL.crypto.X509Extension`
:type ips: `list` of (`ipaddress.IPv4Address` or `ipaddress.IPv6Address`)
If more than one domain is provided, all of the domains are put into
``subjectAltName`` X.509 extension and first domain is set as the
subject CN. If only one domain is provided no ``subjectAltName``
extension is used, unless `force_san` is ``True``. | def gen_ss_cert(key: crypto.PKey, domains: Optional[List[str]] = None,
not_before: Optional[int] = None,
validity: int = (7 * 24 * 60 * 60), force_san: bool = True,
extensions: Optional[List[crypto.X509Extension]] = None,
ips: Optional[List[Union[ipaddress.IPv4Address, ipaddress.IPv6Address]]] = None
) -> crypto.X509:
"""Generate new self-signed certificate.
:type domains: `list` of `str`
:param OpenSSL.crypto.PKey key:
:param bool force_san:
:param extensions: List of additional extensions to include in the cert.
:type extensions: `list` of `OpenSSL.crypto.X509Extension`
:type ips: `list` of (`ipaddress.IPv4Address` or `ipaddress.IPv6Address`)
If more than one domain is provided, all of the domains are put into
``subjectAltName`` X.509 extension and first domain is set as the
subject CN. If only one domain is provided no ``subjectAltName``
extension is used, unless `force_san` is ``True``.
"""
assert domains or ips, "Must provide one or more hostnames or IPs for the cert."
cert = crypto.X509()
cert.set_serial_number(int(binascii.hexlify(os.urandom(16)), 16))
cert.set_version(2)
if extensions is None:
extensions = []
if domains is None:
domains = []
if ips is None:
ips = []
extensions.append(
crypto.X509Extension(
b"basicConstraints", True, b"CA:TRUE, pathlen:0"),
)
if len(domains) > 0:
cert.get_subject().CN = domains[0]
# TODO: what to put into cert.get_subject()?
cert.set_issuer(cert.get_subject())
sanlist = []
for address in domains:
sanlist.append('DNS:' + address)
for ip in ips:
sanlist.append('IP:' + ip.exploded)
san_string = ', '.join(sanlist).encode('ascii')
if force_san or len(domains) > 1 or len(ips) > 0:
extensions.append(crypto.X509Extension(
b"subjectAltName",
critical=False,
value=san_string
))
cert.add_extensions(extensions)
cert.gmtime_adj_notBefore(0 if not_before is None else not_before)
cert.gmtime_adj_notAfter(validity)
cert.set_pubkey(key)
cert.sign(key, "sha256")
return cert |
Dump certificate chain into a bundle.
:param list chain: List of `OpenSSL.crypto.X509` (or wrapped in
:class:`josepy.util.ComparableX509`).
:returns: certificate chain bundle
:rtype: bytes | def dump_pyopenssl_chain(chain: Union[List[jose.ComparableX509], List[crypto.X509]],
filetype: int = crypto.FILETYPE_PEM) -> bytes:
"""Dump certificate chain into a bundle.
:param list chain: List of `OpenSSL.crypto.X509` (or wrapped in
:class:`josepy.util.ComparableX509`).
:returns: certificate chain bundle
:rtype: bytes
"""
# XXX: returns empty string when no chain is available, which
# shuts up RenewableCert, but might not be the best solution...
def _dump_cert(cert: Union[jose.ComparableX509, crypto.X509]) -> bytes:
if isinstance(cert, jose.ComparableX509):
if isinstance(cert.wrapped, crypto.X509Req):
raise errors.Error("Unexpected CSR provided.") # pragma: no cover
cert = cert.wrapped
return crypto.dump_certificate(filetype, cert)
# assumes that OpenSSL.crypto.dump_certificate includes ending
# newline character
return b"".join(_dump_cert(cert) for cert in chain) |
Generates a type-friendly Fixed field. | def fixed(json_name: str, value: Any) -> Any:
"""Generates a type-friendly Fixed field."""
return Fixed(json_name, value) |
Generates a type-friendly RFC3339 field. | def rfc3339(json_name: str, omitempty: bool = False) -> Any:
"""Generates a type-friendly RFC3339 field."""
return RFC3339Field(json_name, omitempty=omitempty) |
Check if argument is an ACME error. | def is_acme_error(err: BaseException) -> bool:
"""Check if argument is an ACME error."""
if isinstance(err, Error) and (err.typ is not None):
return ERROR_PREFIX in err.typ
return False |
Map dictionary keys. | def map_keys(dikt: Mapping[Any, Any], func: Callable[[Any], Any]) -> Dict[Any, Any]:
"""Map dictionary keys."""
return {func(key): value for key, value in dikt.items()} |
Load contents of a test vector. | def load_vector(*names):
"""Load contents of a test vector."""
# luckily, resource_string opens file in binary mode
vector_ref = importlib_resources.files(__package__).joinpath('testdata', *names)
return vector_ref.read_bytes() |
Load certificate. | def load_cert(*names):
"""Load certificate."""
loader = _guess_loader(
names[-1], crypto.FILETYPE_PEM, crypto.FILETYPE_ASN1)
return crypto.load_certificate(loader, load_vector(*names)) |
Load ComparableX509 cert. | def load_comparable_cert(*names):
"""Load ComparableX509 cert."""
return jose.ComparableX509(load_cert(*names)) |
Load certificate request. | def load_csr(*names):
"""Load certificate request."""
loader = _guess_loader(
names[-1], crypto.FILETYPE_PEM, crypto.FILETYPE_ASN1)
return crypto.load_certificate_request(loader, load_vector(*names)) |
Load ComparableX509 certificate request. | def load_comparable_csr(*names):
"""Load ComparableX509 certificate request."""
return jose.ComparableX509(load_csr(*names)) |
Load RSA private key. | def load_rsa_private_key(*names):
"""Load RSA private key."""
loader = _guess_loader(names[-1], serialization.load_pem_private_key,
serialization.load_der_private_key)
return jose.ComparableRSAKey(loader(
load_vector(*names), password=None, backend=default_backend())) |
Load ECDSA private key. | def load_ecdsa_private_key(*names):
"""Load ECDSA private key."""
loader = _guess_loader(names[-1], serialization.load_pem_private_key,
serialization.load_der_private_key)
return ComparableECKey(loader(
load_vector(*names), password=None, backend=default_backend())) |
Load pyOpenSSL private key. | def load_pyopenssl_private_key(*names):
"""Load pyOpenSSL private key."""
loader = _guess_loader(
names[-1], crypto.FILETYPE_PEM, crypto.FILETYPE_ASN1)
return crypto.load_privatekey(loader, load_vector(*names)) |
Create certificate signing request. | def new_csr_comp(domain_name, pkey_pem=None):
"""Create certificate signing request."""
if pkey_pem is None:
# Create private key.
pkey = OpenSSL.crypto.PKey()
pkey.generate_key(OpenSSL.crypto.TYPE_RSA, CERT_PKEY_BITS)
pkey_pem = OpenSSL.crypto.dump_privatekey(OpenSSL.crypto.FILETYPE_PEM,
pkey)
csr_pem = crypto_util.make_csr(pkey_pem, [domain_name])
return pkey_pem, csr_pem |
Extract authorization resource from within order resource. | def select_http01_chall(orderr):
"""Extract authorization resource from within order resource."""
# Authorization Resource: authz.
# This object holds the offered challenges by the server and their status.
authz_list = orderr.authorizations
for authz in authz_list:
# Choosing challenge.
# authz.body.challenges is a set of ChallengeBody objects.
for i in authz.body.challenges:
# Find the supported challenge.
if isinstance(i.chall, challenges.HTTP01):
return i
raise Exception('HTTP-01 challenge was not offered by the CA server.') |
Manage standalone server set up and shutdown. | def challenge_server(http_01_resources):
"""Manage standalone server set up and shutdown."""
# Setting up a fake server that binds at PORT and any address.
address = ('', PORT)
try:
servers = standalone.HTTP01DualNetworkedServers(address,
http_01_resources)
# Start client standalone web server.
servers.serve_forever()
yield servers
finally:
# Shutdown client web server and unbind from PORT
servers.shutdown_and_server_close() |
Set up standalone webserver and perform HTTP-01 challenge. | def perform_http01(client_acme, challb, orderr):
"""Set up standalone webserver and perform HTTP-01 challenge."""
response, validation = challb.response_and_validation(client_acme.net.key)
resource = standalone.HTTP01RequestHandler.HTTP01Resource(
chall=challb.chall, response=response, validation=validation)
with challenge_server({resource}):
# Let the CA server know that we are ready for the challenge.
client_acme.answer_challenge(challb, response)
# Wait for challenge status and then issue a certificate.
# It is possible to set a deadline time.
finalized_orderr = client_acme.poll_and_finalize(orderr)
return finalized_orderr.fullchain_pem |
This example executes the whole process of fulfilling a HTTP-01
challenge for one specific domain.
The workflow consists of:
(Account creation)
- Create account key
- Register account and accept TOS
(Certificate actions)
- Select HTTP-01 within offered challenges by the CA server
- Set up http challenge resource
- Set up standalone web server
- Create domain private key and CSR
- Issue certificate
- Renew certificate
- Revoke certificate
(Account update actions)
- Change contact information
- Deactivate Account | def example_http():
"""This example executes the whole process of fulfilling a HTTP-01
challenge for one specific domain.
The workflow consists of:
(Account creation)
- Create account key
- Register account and accept TOS
(Certificate actions)
- Select HTTP-01 within offered challenges by the CA server
- Set up http challenge resource
- Set up standalone web server
- Create domain private key and CSR
- Issue certificate
- Renew certificate
- Revoke certificate
(Account update actions)
- Change contact information
- Deactivate Account
"""
# Create account key
acc_key = jose.JWKRSA(
key=rsa.generate_private_key(public_exponent=65537,
key_size=ACC_KEY_BITS,
backend=default_backend()))
# Register account and accept TOS
net = client.ClientNetwork(acc_key, user_agent=USER_AGENT)
directory = client.ClientV2.get_directory(DIRECTORY_URL, net)
client_acme = client.ClientV2(directory, net=net)
# Terms of Service URL is in client_acme.directory.meta.terms_of_service
# Registration Resource: regr
# Creates account with contact information.
email = ('[email protected]')
regr = client_acme.new_account(
messages.NewRegistration.from_data(
email=email, terms_of_service_agreed=True))
# Create domain private key and CSR
pkey_pem, csr_pem = new_csr_comp(DOMAIN)
# Issue certificate
orderr = client_acme.new_order(csr_pem)
# Select HTTP-01 within offered challenges by the CA server
challb = select_http01_chall(orderr)
# The certificate is ready to be used in the variable "fullchain_pem".
fullchain_pem = perform_http01(client_acme, challb, orderr)
# Renew certificate
_, csr_pem = new_csr_comp(DOMAIN, pkey_pem)
orderr = client_acme.new_order(csr_pem)
challb = select_http01_chall(orderr)
# Performing challenge
fullchain_pem = perform_http01(client_acme, challb, orderr)
# Revoke certificate
fullchain_com = jose.ComparableX509(
OpenSSL.crypto.load_certificate(
OpenSSL.crypto.FILETYPE_PEM, fullchain_pem))
try:
client_acme.revoke(fullchain_com, 0) # revocation reason = 0
except errors.ConflictError:
# Certificate already revoked.
pass
# Query registration status.
client_acme.net.account = regr
try:
regr = client_acme.query_registration(regr)
except errors.Error as err:
if err.typ == messages.ERROR_PREFIX + 'unauthorized':
# Status is deactivated.
pass
raise
# Change contact information
email = '[email protected]'
regr = client_acme.update_registration(
regr.update(
body=regr.body.update(
contact=('mailto:' + email,)
)
)
)
# Deactivate account/registration
regr = client_acme.deactivate_registration(regr) |
Read unicode from given file. | def read_file(filename, encoding='utf8'):
"""Read unicode from given file."""
with codecs.open(filename, encoding=encoding) as fd:
return fd.read() |
Validate command line options and display error message if
requirements are not met.
:param config: NamespaceConfig instance holding user configuration
:type args: :class:`certbot.configuration.NamespaceConfig` | def _check_config_sanity(config: NamespaceConfig) -> None:
"""Validate command line options and display error message if
requirements are not met.
:param config: NamespaceConfig instance holding user configuration
:type args: :class:`certbot.configuration.NamespaceConfig`
"""
# Port check
if config.http01_port == config.https_port:
raise errors.ConfigurationError(
"Trying to run http-01 and https-port "
"on the same port ({0})".format(config.https_port))
# Domain checks
if config.namespace.domains is not None:
for domain in config.namespace.domains:
# This may be redundant, but let's be paranoid
util.enforce_domain_sanity(domain) |
Is value of an immutable type? | def _is_immutable(value: Any) -> bool:
"""Is value of an immutable type?"""
if isinstance(value, tuple):
# tuples are only immutable if all contained values are immutable.
return all(_is_immutable(subvalue) for subvalue in value)
for immutable_type in (int, float, complex, str, bytes, bool, frozenset,):
if isinstance(value, immutable_type):
return True
# The last case we consider here is None which is also immutable.
return value is None |
Initializes and saves a privkey.
Inits key and saves it in PEM format on the filesystem.
.. note:: keyname is the attempted filename, it may be different if a file
already exists at the path.
:param int key_size: key size in bits if key size is rsa.
:param str key_dir: Optional key save directory.
:param str key_type: Key Type [rsa, ecdsa]
:param str elliptic_curve: Name of the elliptic curve if key type is ecdsa.
:param str keyname: Filename of key
:param bool strict_permissions: If true and key_dir exists, an exception is raised if
the directory doesn't have 0700 permissions or isn't owned by the current user.
:returns: Key
:rtype: :class:`certbot.util.Key`
:raises ValueError: If unable to generate the key given key_size. | def generate_key(key_size: int, key_dir: Optional[str], key_type: str = "rsa",
elliptic_curve: str = "secp256r1", keyname: str = "key-certbot.pem",
strict_permissions: bool = True) -> util.Key:
"""Initializes and saves a privkey.
Inits key and saves it in PEM format on the filesystem.
.. note:: keyname is the attempted filename, it may be different if a file
already exists at the path.
:param int key_size: key size in bits if key size is rsa.
:param str key_dir: Optional key save directory.
:param str key_type: Key Type [rsa, ecdsa]
:param str elliptic_curve: Name of the elliptic curve if key type is ecdsa.
:param str keyname: Filename of key
:param bool strict_permissions: If true and key_dir exists, an exception is raised if
the directory doesn't have 0700 permissions or isn't owned by the current user.
:returns: Key
:rtype: :class:`certbot.util.Key`
:raises ValueError: If unable to generate the key given key_size.
"""
try:
key_pem = make_key(
bits=key_size, elliptic_curve=elliptic_curve or "secp256r1", key_type=key_type,
)
except ValueError as err:
logger.debug("", exc_info=True)
logger.error("Encountered error while making key: %s", str(err))
raise err
# Save file
key_path = None
if key_dir:
util.make_or_verify_dir(key_dir, 0o700, strict_permissions)
key_f, key_path = util.unique_file(
os.path.join(key_dir, keyname), 0o600, "wb")
with key_f:
key_f.write(key_pem)
if key_type == 'rsa':
logger.debug("Generating RSA key (%d bits): %s", key_size, key_path)
else:
logger.debug("Generating ECDSA key (%d bits): %s", key_size, key_path)
return util.Key(key_path, key_pem) |
Initialize a CSR with the given private key.
:param privkey: Key to include in the CSR
:type privkey: :class:`certbot.util.Key`
:param set names: `str` names to include in the CSR
:param str path: Optional certificate save directory.
:param bool must_staple: If true, include the TLS Feature extension "OCSP Must-Staple"
:param bool strict_permissions: If true and path exists, an exception is raised if
the directory doesn't have 0755 permissions or isn't owned by the current user.
:returns: CSR
:rtype: :class:`certbot.util.CSR` | def generate_csr(privkey: util.Key, names: Union[List[str], Set[str]], path: Optional[str],
must_staple: bool = False, strict_permissions: bool = True) -> util.CSR:
"""Initialize a CSR with the given private key.
:param privkey: Key to include in the CSR
:type privkey: :class:`certbot.util.Key`
:param set names: `str` names to include in the CSR
:param str path: Optional certificate save directory.
:param bool must_staple: If true, include the TLS Feature extension "OCSP Must-Staple"
:param bool strict_permissions: If true and path exists, an exception is raised if
the directory doesn't have 0755 permissions or isn't owned by the current user.
:returns: CSR
:rtype: :class:`certbot.util.CSR`
"""
csr_pem = acme_crypto_util.make_csr(
privkey.pem, names, must_staple=must_staple)
# Save CSR, if requested
csr_filename = None
if path:
util.make_or_verify_dir(path, 0o755, strict_permissions)
csr_f, csr_filename = util.unique_file(
os.path.join(path, "csr-certbot.pem"), 0o644, "wb")
with csr_f:
csr_f.write(csr_pem)
logger.debug("Creating CSR: %s", csr_filename)
return util.CSR(csr_filename, csr_pem, "pem") |
Validate CSR.
Check if `csr` is a valid CSR for the given domains.
:param bytes csr: CSR in PEM.
:returns: Validity of CSR.
:rtype: bool | def valid_csr(csr: bytes) -> bool:
"""Validate CSR.
Check if `csr` is a valid CSR for the given domains.
:param bytes csr: CSR in PEM.
:returns: Validity of CSR.
:rtype: bool
"""
try:
req = crypto.load_certificate_request(
crypto.FILETYPE_PEM, csr)
return req.verify(req.get_pubkey())
except crypto.Error:
logger.debug("", exc_info=True)
return False |
Does private key correspond to the subject public key in the CSR?
:param bytes csr: CSR in PEM.
:param bytes privkey: Private key file contents (PEM)
:returns: Correspondence of private key to CSR subject public key.
:rtype: bool | def csr_matches_pubkey(csr: bytes, privkey: bytes) -> bool:
"""Does private key correspond to the subject public key in the CSR?
:param bytes csr: CSR in PEM.
:param bytes privkey: Private key file contents (PEM)
:returns: Correspondence of private key to CSR subject public key.
:rtype: bool
"""
req = crypto.load_certificate_request(
crypto.FILETYPE_PEM, csr)
pkey = crypto.load_privatekey(crypto.FILETYPE_PEM, privkey)
try:
return req.verify(pkey)
except crypto.Error:
logger.debug("", exc_info=True)
return False |
Import a CSR file, which can be either PEM or DER.
:param str csrfile: CSR filename
:param bytes data: contents of the CSR file
:returns: (`crypto.FILETYPE_PEM`,
util.CSR object representing the CSR,
list of domains requested in the CSR)
:rtype: tuple | def import_csr_file(csrfile: str, data: bytes) -> Tuple[int, util.CSR, List[str]]:
"""Import a CSR file, which can be either PEM or DER.
:param str csrfile: CSR filename
:param bytes data: contents of the CSR file
:returns: (`crypto.FILETYPE_PEM`,
util.CSR object representing the CSR,
list of domains requested in the CSR)
:rtype: tuple
"""
PEM = crypto.FILETYPE_PEM
load = crypto.load_certificate_request
try:
# Try to parse as DER first, then fall back to PEM.
csr = load(crypto.FILETYPE_ASN1, data)
except crypto.Error:
try:
csr = load(PEM, data)
except crypto.Error:
raise errors.Error("Failed to parse CSR file: {0}".format(csrfile))
domains = _get_names_from_loaded_cert_or_req(csr)
# Internally we always use PEM, so re-encode as PEM before returning.
data_pem = crypto.dump_certificate_request(PEM, csr)
return PEM, util.CSR(file=csrfile, data=data_pem, form="pem"), domains |
Generate PEM encoded RSA|EC key.
:param int bits: Number of bits if key_type=rsa. At least 2048 for RSA.
:param str key_type: The type of key to generate, but be rsa or ecdsa
:param str elliptic_curve: The elliptic curve to use.
:returns: new RSA or ECDSA key in PEM form with specified number of bits
or of type ec_curve when key_type ecdsa is used.
:rtype: str | def make_key(bits: int = 2048, key_type: str = "rsa",
elliptic_curve: Optional[str] = None) -> bytes:
"""Generate PEM encoded RSA|EC key.
:param int bits: Number of bits if key_type=rsa. At least 2048 for RSA.
:param str key_type: The type of key to generate, but be rsa or ecdsa
:param str elliptic_curve: The elliptic curve to use.
:returns: new RSA or ECDSA key in PEM form with specified number of bits
or of type ec_curve when key_type ecdsa is used.
:rtype: str
"""
if key_type == 'rsa':
if bits < 2048:
raise errors.Error("Unsupported RSA key length: {}".format(bits))
key = crypto.PKey()
key.generate_key(crypto.TYPE_RSA, bits)
elif key_type == 'ecdsa':
if not elliptic_curve:
raise errors.Error("When key_type == ecdsa, elliptic_curve must be set.")
try:
name = elliptic_curve.upper()
if name in ('SECP256R1', 'SECP384R1', 'SECP521R1'):
curve = getattr(ec, elliptic_curve.upper())
if not curve:
raise errors.Error(f"Invalid curve type: {elliptic_curve}")
_key = ec.generate_private_key(
curve=curve(),
backend=default_backend()
)
else:
raise errors.Error("Unsupported elliptic curve: {}".format(elliptic_curve))
except TypeError:
raise errors.Error("Unsupported elliptic curve: {}".format(elliptic_curve))
except UnsupportedAlgorithm as e:
raise e from errors.Error(str(e))
_key_pem = _key.private_bytes(
encoding=Encoding.PEM,
format=PrivateFormat.TraditionalOpenSSL,
encryption_algorithm=NoEncryption()
)
key = crypto.load_privatekey(crypto.FILETYPE_PEM, _key_pem)
else:
raise errors.Error("Invalid key_type specified: {}. Use [rsa|ecdsa]".format(key_type))
return crypto.dump_privatekey(crypto.FILETYPE_PEM, key) |
Is valid RSA private key?
:param privkey: Private key file contents in PEM
:returns: Validity of private key.
:rtype: bool | def valid_privkey(privkey: Union[str, bytes]) -> bool:
"""Is valid RSA private key?
:param privkey: Private key file contents in PEM
:returns: Validity of private key.
:rtype: bool
"""
try:
return crypto.load_privatekey(
crypto.FILETYPE_PEM, privkey).check()
except (TypeError, crypto.Error):
return False |
For checking that your certs were not corrupted on disk.
Several things are checked:
1. Signature verification for the cert.
2. That fullchain matches cert and chain when concatenated.
3. Check that the private key matches the certificate.
:param renewable_cert: cert to verify
:type renewable_cert: certbot.interfaces.RenewableCert
:raises errors.Error: If verification fails. | def verify_renewable_cert(renewable_cert: interfaces.RenewableCert) -> None:
"""For checking that your certs were not corrupted on disk.
Several things are checked:
1. Signature verification for the cert.
2. That fullchain matches cert and chain when concatenated.
3. Check that the private key matches the certificate.
:param renewable_cert: cert to verify
:type renewable_cert: certbot.interfaces.RenewableCert
:raises errors.Error: If verification fails.
"""
verify_renewable_cert_sig(renewable_cert)
verify_fullchain(renewable_cert)
verify_cert_matches_priv_key(renewable_cert.cert_path, renewable_cert.key_path) |
Verifies the signature of a RenewableCert object.
:param renewable_cert: cert to verify
:type renewable_cert: certbot.interfaces.RenewableCert
:raises errors.Error: If signature verification fails. | def verify_renewable_cert_sig(renewable_cert: interfaces.RenewableCert) -> None:
"""Verifies the signature of a RenewableCert object.
:param renewable_cert: cert to verify
:type renewable_cert: certbot.interfaces.RenewableCert
:raises errors.Error: If signature verification fails.
"""
try:
with open(renewable_cert.chain_path, 'rb') as chain_file:
chain = x509.load_pem_x509_certificate(chain_file.read(), default_backend())
with open(renewable_cert.cert_path, 'rb') as cert_file:
cert = x509.load_pem_x509_certificate(cert_file.read(), default_backend())
pk = chain.public_key()
assert cert.signature_hash_algorithm # always present for RSA and ECDSA
verify_signed_payload(pk, cert.signature, cert.tbs_certificate_bytes,
cert.signature_hash_algorithm)
except (IOError, ValueError, InvalidSignature) as e:
error_str = "verifying the signature of the certificate located at {0} has failed. \
Details: {1}".format(renewable_cert.cert_path, e)
logger.exception(error_str)
raise errors.Error(error_str) |
Check the signature of a payload.
:param RSAPublicKey/EllipticCurvePublicKey public_key: the public_key to check signature
:param bytes signature: the signature bytes
:param bytes payload: the payload bytes
:param hashes.HashAlgorithm signature_hash_algorithm: algorithm used to hash the payload
:raises InvalidSignature: If signature verification fails.
:raises errors.Error: If public key type is not supported | def verify_signed_payload(public_key: Union[DSAPublicKey, 'Ed25519PublicKey', 'Ed448PublicKey',
EllipticCurvePublicKey, RSAPublicKey,
'X25519PublicKey', 'X448PublicKey'],
signature: bytes, payload: bytes,
signature_hash_algorithm: hashes.HashAlgorithm) -> None:
"""Check the signature of a payload.
:param RSAPublicKey/EllipticCurvePublicKey public_key: the public_key to check signature
:param bytes signature: the signature bytes
:param bytes payload: the payload bytes
:param hashes.HashAlgorithm signature_hash_algorithm: algorithm used to hash the payload
:raises InvalidSignature: If signature verification fails.
:raises errors.Error: If public key type is not supported
"""
if isinstance(public_key, RSAPublicKey):
public_key.verify(
signature, payload, PKCS1v15(), signature_hash_algorithm
)
elif isinstance(public_key, EllipticCurvePublicKey):
public_key.verify(
signature, payload, ECDSA(signature_hash_algorithm)
)
else:
raise errors.Error("Unsupported public key type.") |
Verifies that the private key and cert match.
:param str cert_path: path to a cert in PEM format
:param str key_path: path to a private key file
:raises errors.Error: If they don't match. | def verify_cert_matches_priv_key(cert_path: str, key_path: str) -> None:
""" Verifies that the private key and cert match.
:param str cert_path: path to a cert in PEM format
:param str key_path: path to a private key file
:raises errors.Error: If they don't match.
"""
try:
context = SSL.Context(SSL.SSLv23_METHOD)
context.use_certificate_file(cert_path)
context.use_privatekey_file(key_path)
context.check_privatekey()
except (IOError, SSL.Error) as e:
error_str = "verifying the certificate located at {0} matches the \
private key located at {1} has failed. \
Details: {2}".format(cert_path,
key_path, e)
logger.exception(error_str)
raise errors.Error(error_str) |
Verifies that fullchain is indeed cert concatenated with chain.
:param renewable_cert: cert to verify
:type renewable_cert: certbot.interfaces.RenewableCert
:raises errors.Error: If cert and chain do not combine to fullchain. | def verify_fullchain(renewable_cert: interfaces.RenewableCert) -> None:
""" Verifies that fullchain is indeed cert concatenated with chain.
:param renewable_cert: cert to verify
:type renewable_cert: certbot.interfaces.RenewableCert
:raises errors.Error: If cert and chain do not combine to fullchain.
"""
try:
with open(renewable_cert.chain_path) as chain_file:
chain = chain_file.read()
with open(renewable_cert.cert_path) as cert_file:
cert = cert_file.read()
with open(renewable_cert.fullchain_path) as fullchain_file:
fullchain = fullchain_file.read()
if (cert + chain) != fullchain:
error_str = "fullchain does not match cert + chain for {0}!"
error_str = error_str.format(renewable_cert.lineagename)
raise errors.Error(error_str)
except IOError as e:
error_str = "reading one of cert, chain, or fullchain has failed: {0}".format(e)
logger.exception(error_str)
raise errors.Error(error_str)
except errors.Error as e:
raise e |
Load PEM/DER certificate.
:raises errors.Error: | def pyopenssl_load_certificate(data: bytes) -> Tuple[crypto.X509, int]:
"""Load PEM/DER certificate.
:raises errors.Error:
"""
openssl_errors = []
for file_type in (crypto.FILETYPE_PEM, crypto.FILETYPE_ASN1):
try:
return crypto.load_certificate(file_type, data), file_type
except crypto.Error as error: # TODO: other errors?
openssl_errors.append(error)
raise errors.Error("Unable to load: {0}".format(",".join(
str(error) for error in openssl_errors))) |
Get a list of Subject Alternative Names from a certificate.
:param str cert: Certificate (encoded).
:param typ: `crypto.FILETYPE_PEM` or `crypto.FILETYPE_ASN1`
:returns: A list of Subject Alternative Names.
:rtype: list | def get_sans_from_cert(cert: bytes, typ: int = crypto.FILETYPE_PEM) -> List[str]:
"""Get a list of Subject Alternative Names from a certificate.
:param str cert: Certificate (encoded).
:param typ: `crypto.FILETYPE_PEM` or `crypto.FILETYPE_ASN1`
:returns: A list of Subject Alternative Names.
:rtype: list
"""
return _get_sans_from_cert_or_req(
cert, crypto.load_certificate, typ) |
Get a list of domains from a cert, including the CN if it is set.
:param str cert: Certificate (encoded).
:param typ: `crypto.FILETYPE_PEM` or `crypto.FILETYPE_ASN1`
:returns: A list of domain names.
:rtype: list | def get_names_from_cert(cert: bytes, typ: int = crypto.FILETYPE_PEM) -> List[str]:
"""Get a list of domains from a cert, including the CN if it is set.
:param str cert: Certificate (encoded).
:param typ: `crypto.FILETYPE_PEM` or `crypto.FILETYPE_ASN1`
:returns: A list of domain names.
:rtype: list
"""
return _get_names_from_cert_or_req(
cert, crypto.load_certificate, typ) |
Get a list of domains from a CSR, including the CN if it is set.
:param str csr: CSR (encoded).
:param typ: `crypto.FILETYPE_PEM` or `crypto.FILETYPE_ASN1`
:returns: A list of domain names.
:rtype: list | def get_names_from_req(csr: bytes, typ: int = crypto.FILETYPE_PEM) -> List[str]:
"""Get a list of domains from a CSR, including the CN if it is set.
:param str csr: CSR (encoded).
:param typ: `crypto.FILETYPE_PEM` or `crypto.FILETYPE_ASN1`
:returns: A list of domain names.
:rtype: list
"""
return _get_names_from_cert_or_req(csr, crypto.load_certificate_request, typ) |
Dump certificate chain into a bundle.
:param list chain: List of `crypto.X509` (or wrapped in
:class:`josepy.util.ComparableX509`). | def dump_pyopenssl_chain(chain: Union[List[crypto.X509], List[josepy.ComparableX509]],
filetype: int = crypto.FILETYPE_PEM) -> bytes:
"""Dump certificate chain into a bundle.
:param list chain: List of `crypto.X509` (or wrapped in
:class:`josepy.util.ComparableX509`).
"""
# XXX: returns empty string when no chain is available, which
# shuts up RenewableCert, but might not be the best solution...
return acme_crypto_util.dump_pyopenssl_chain(chain, filetype) |
When does the cert at cert_path start being valid?
:param str cert_path: path to a cert in PEM format
:returns: the notBefore value from the cert at cert_path
:rtype: :class:`datetime.datetime` | def notBefore(cert_path: str) -> datetime.datetime:
"""When does the cert at cert_path start being valid?
:param str cert_path: path to a cert in PEM format
:returns: the notBefore value from the cert at cert_path
:rtype: :class:`datetime.datetime`
"""
return _notAfterBefore(cert_path, crypto.X509.get_notBefore) |
When does the cert at cert_path stop being valid?
:param str cert_path: path to a cert in PEM format
:returns: the notAfter value from the cert at cert_path
:rtype: :class:`datetime.datetime` | def notAfter(cert_path: str) -> datetime.datetime:
"""When does the cert at cert_path stop being valid?
:param str cert_path: path to a cert in PEM format
:returns: the notAfter value from the cert at cert_path
:rtype: :class:`datetime.datetime`
"""
return _notAfterBefore(cert_path, crypto.X509.get_notAfter) |
Internal helper function for finding notbefore/notafter.
:param str cert_path: path to a cert in PEM format
:param function method: one of ``crypto.X509.get_notBefore``
or ``crypto.X509.get_notAfter``
:returns: the notBefore or notAfter value from the cert at cert_path
:rtype: :class:`datetime.datetime` | def _notAfterBefore(cert_path: str,
method: Callable[[crypto.X509], Optional[bytes]]) -> datetime.datetime:
"""Internal helper function for finding notbefore/notafter.
:param str cert_path: path to a cert in PEM format
:param function method: one of ``crypto.X509.get_notBefore``
or ``crypto.X509.get_notAfter``
:returns: the notBefore or notAfter value from the cert at cert_path
:rtype: :class:`datetime.datetime`
"""
# pylint: disable=redefined-outer-name
with open(cert_path, "rb") as f:
x509 = crypto.load_certificate(crypto.FILETYPE_PEM, f.read())
# pyopenssl always returns bytes
timestamp = method(x509)
if not timestamp:
raise errors.Error("Error while invoking timestamp method, None has been returned.")
reformatted_timestamp = [timestamp[0:4], b"-", timestamp[4:6], b"-",
timestamp[6:8], b"T", timestamp[8:10], b":",
timestamp[10:12], b":", timestamp[12:]]
# pyrfc3339 always uses the type `str`
timestamp_bytes = b"".join(reformatted_timestamp)
timestamp_str = timestamp_bytes.decode('ascii')
return pyrfc3339.parse(timestamp_str) |
Compute a sha256sum of a file.
NB: In given file, platform specific newlines characters will be converted
into their equivalent unicode counterparts before calculating the hash.
:param str filename: path to the file whose hash will be computed
:returns: sha256 digest of the file in hexadecimal
:rtype: str | def sha256sum(filename: str) -> str:
"""Compute a sha256sum of a file.
NB: In given file, platform specific newlines characters will be converted
into their equivalent unicode counterparts before calculating the hash.
:param str filename: path to the file whose hash will be computed
:returns: sha256 digest of the file in hexadecimal
:rtype: str
"""
sha256 = hashlib.sha256()
with open(filename, 'r') as file_d:
sha256.update(file_d.read().encode('UTF-8'))
return sha256.hexdigest() |
Split fullchain_pem into cert_pem and chain_pem
:param str fullchain_pem: concatenated cert + chain
:returns: tuple of string cert_pem and chain_pem
:rtype: tuple
:raises errors.Error: If there are less than 2 certificates in the chain. | def cert_and_chain_from_fullchain(fullchain_pem: str) -> Tuple[str, str]:
"""Split fullchain_pem into cert_pem and chain_pem
:param str fullchain_pem: concatenated cert + chain
:returns: tuple of string cert_pem and chain_pem
:rtype: tuple
:raises errors.Error: If there are less than 2 certificates in the chain.
"""
# First pass: find the boundary of each certificate in the chain.
# TODO: This will silently skip over any "explanatory text" in between boundaries,
# which is prohibited by RFC8555.
certs = CERT_PEM_REGEX.findall(fullchain_pem.encode())
if len(certs) < 2:
raise errors.Error("failed to parse fullchain into cert and chain: " +
"less than 2 certificates in chain")
# Second pass: for each certificate found, parse it using OpenSSL and re-encode it,
# with the effect of normalizing any encoding variations (e.g. CRLF, whitespace).
certs_normalized = [crypto.dump_certificate(crypto.FILETYPE_PEM,
crypto.load_certificate(crypto.FILETYPE_PEM, cert)).decode() for cert in certs]
# Since each normalized cert has a newline suffix, no extra newlines are required.
return (certs_normalized[0], "".join(certs_normalized[1:])) |
Retrieve the serial number of a certificate from certificate path
:param str cert_path: path to a cert in PEM format
:returns: serial number of the certificate
:rtype: int | def get_serial_from_cert(cert_path: str) -> int:
"""Retrieve the serial number of a certificate from certificate path
:param str cert_path: path to a cert in PEM format
:returns: serial number of the certificate
:rtype: int
"""
# pylint: disable=redefined-outer-name
with open(cert_path, "rb") as f:
x509 = crypto.load_certificate(crypto.FILETYPE_PEM, f.read())
return x509.get_serial_number() |
Chooses the first certificate chain from fullchains whose topmost
intermediate has an Issuer Common Name matching issuer_cn (in other words
the first chain which chains to a root whose name matches issuer_cn).
:param fullchains: The list of fullchains in PEM chain format.
:type fullchains: `list` of `str`
:param `str` issuer_cn: The exact Subject Common Name to match against any
issuer in the certificate chain.
:returns: The best-matching fullchain, PEM-encoded, or the first if none match.
:rtype: `str` | def find_chain_with_issuer(fullchains: List[str], issuer_cn: str,
warn_on_no_match: bool = False) -> str:
"""Chooses the first certificate chain from fullchains whose topmost
intermediate has an Issuer Common Name matching issuer_cn (in other words
the first chain which chains to a root whose name matches issuer_cn).
:param fullchains: The list of fullchains in PEM chain format.
:type fullchains: `list` of `str`
:param `str` issuer_cn: The exact Subject Common Name to match against any
issuer in the certificate chain.
:returns: The best-matching fullchain, PEM-encoded, or the first if none match.
:rtype: `str`
"""
for chain in fullchains:
certs = CERT_PEM_REGEX.findall(chain.encode())
top_cert = x509.load_pem_x509_certificate(certs[-1], default_backend())
top_issuer_cn = top_cert.issuer.get_attributes_for_oid(x509.NameOID.COMMON_NAME)
if top_issuer_cn and top_issuer_cn[0].value == issuer_cn:
return chain
# Nothing matched, return whatever was first in the list.
if warn_on_no_match:
logger.warning("Certbot has been configured to prefer certificate chains with "
"issuer '%s', but no chain from the CA matched this issuer. Using "
"the default certificate chain instead.", issuer_cn)
return fullchains[0] |
Run Certbot.
:param cli_args: command line to Certbot, defaults to ``sys.argv[1:]``
:type cli_args: `list` of `str`
:returns: value for `sys.exit` about the exit status of Certbot
:rtype: `str` or `int` or `None` | def main(cli_args: Optional[List[str]] = None) -> Optional[Union[str, int]]:
"""Run Certbot.
:param cli_args: command line to Certbot, defaults to ``sys.argv[1:]``
:type cli_args: `list` of `str`
:returns: value for `sys.exit` about the exit status of Certbot
:rtype: `str` or `int` or `None`
"""
return internal_main.main(cli_args) |
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) | def _determine_ocsp_server(cert_path: str) -> Tuple[Optional[str], Optional[str]]:
"""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)
"""
with open(cert_path, 'rb') as file_handler:
cert = x509.load_pem_x509_certificate(file_handler.read(), default_backend())
try:
extension = cert.extensions.get_extension_for_class(x509.AuthorityInformationAccess)
ocsp_oid = x509.AuthorityInformationAccessOID.OCSP
descriptions = [description for description in extension.value
if description.access_method == ocsp_oid]
url = descriptions[0].access_location.value
except (x509.ExtensionNotFound, IndexError):
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
logger.info("Cannot process OCSP host from URL (%s) in certificate at %s", url, cert_path)
return None, None |
Verify that the OCSP is valid for several criteria | def _check_ocsp_response(response_ocsp: 'ocsp.OCSPResponse', request_ocsp: 'ocsp.OCSPRequest',
issuer_cert: x509.Certificate, cert_path: str) -> None:
"""Verify that the OCSP is valid for several criteria"""
# Assert OCSP response corresponds to the certificate we are talking about
if response_ocsp.serial_number != request_ocsp.serial_number:
raise AssertionError('the certificate in response does not correspond '
'to the certificate in request')
# Assert signature is valid
_check_ocsp_response_signature(response_ocsp, issuer_cert, cert_path)
# Assert issuer in response is the expected one
if (not isinstance(response_ocsp.hash_algorithm, type(request_ocsp.hash_algorithm))
or response_ocsp.issuer_key_hash != request_ocsp.issuer_key_hash
or response_ocsp.issuer_name_hash != request_ocsp.issuer_name_hash):
raise AssertionError('the issuer does not correspond to issuer of the certificate.')
# In following checks, two situations can occur:
# * nextUpdate is set, and requirement is thisUpdate < now < nextUpdate
# * nextUpdate is not set, and requirement is thisUpdate < now
# NB1: We add a validity period tolerance to handle clock time inconsistencies,
# value is 5 min like for OpenSSL.
# NB2: Another check is to verify that thisUpdate is not too old, it is optional
# for OpenSSL, so we do not do it here.
# See OpenSSL implementation as a reference:
# https://github.com/openssl/openssl/blob/ef45aa14c5af024fcb8bef1c9007f3d1c115bd85/crypto/ocsp/ocsp_cl.c#L338-L391
# thisUpdate/nextUpdate are expressed in UTC/GMT time zone
now = datetime.now(pytz.UTC).replace(tzinfo=None)
if not response_ocsp.this_update:
raise AssertionError('param thisUpdate is not set.')
if response_ocsp.this_update > now + timedelta(minutes=5):
raise AssertionError('param thisUpdate is in the future.')
if response_ocsp.next_update and response_ocsp.next_update < now - timedelta(minutes=5):
raise AssertionError('param nextUpdate is in the past.') |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.