How to use the acme.messages function in acme

To help you get started, we’ve selected a few acme examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github letsencrypt / boulder / test / v2_integration.py View on Github external
def test_only_return_existing_reg():
    client = chisel2.uninitialized_client()
    email = "test@not-example.com"
    client.new_account(messages.NewRegistration.from_data(email=email,
            terms_of_service_agreed=True))

    client = chisel2.uninitialized_client(key=client.net.key)
    class extendedAcct(dict):
        def json_dumps(self, indent=None):
            return json.dumps(self)
    acct = extendedAcct({
        "termsOfServiceAgreed": True,
        "contact": [email],
        "onlyReturnExisting": True
    })
    resp = client.net.post(client.directory['newAccount'], acct, acme_version=2)
    if resp.status_code != 200:
        raise(Exception("incorrect response returned for onlyReturnExisting"))

    other_client = chisel2.uninitialized_client()
github certbot / certbot / tools / chisel2.py View on Github external
ok = True
        else:
            raise
    if not ok:
        raise Exception('Expected %s, got no error' % problem_type)

if __name__ == "__main__":
    # Die on SIGINT
    signal.signal(signal.SIGINT, signal.SIG_DFL)
    domains = sys.argv[1:]
    if len(domains) == 0:
        print __doc__
        sys.exit(0)
    try:
        auth_and_issue(domains)
    except messages.Error, e:
        print e
        sys.exit(1)
github freenas / freenas / src / middlewared / middlewared / plugins / crypto.py View on Github external
)
        for domain in data['dns_mapping']:
            if domain not in domains:
                verrors.add(
                    'acme_create.dns_mapping',
                    f'{domain} not specified in the CSR'
                )

        if verrors:
            raise verrors

        acme_client, key = self.get_acme_client_and_key(data['acme_directory_uri'], data['tos'])
        try:
            # perform operations and have a cert issued
            order = acme_client.new_order(csr_data['CSR'])
        except messages.Error as e:
            raise CallError(f'Failed to issue a new order for Certificate : {e}')
        else:
            job.set_progress(progress, 'New order for certificate issuance placed')

            self.handle_authorizations(job, progress, order, data['dns_mapping'], acme_client, key)

            try:
                # Polling for a maximum of 10 minutes while trying to finalize order
                # Should we try .poll() instead first ? research please
                return acme_client.poll_and_finalize(order, datetime.datetime.now() + datetime.timedelta(minutes=10))
            except errors.TimeoutError:
                raise CallError('Certificate request for final order timed out')
github certbot / certbot / acme / acme / client.py View on Github external
"""Request issuance.

        :param csr: CSR
        :type csr: `OpenSSL.crypto.X509Req` wrapped in `.ComparableX509`

        :param authzrs: `list` of `.AuthorizationResource`

        :returns: Issued certificate
        :rtype: `.messages.CertificateResource`

        """
        assert authzrs, "Authorizations list is empty"
        logger.debug("Requesting issuance...")

        # TODO: assert len(authzrs) == number of SANs
        req = messages.CertificateRequest(csr=csr)

        content_type = DER_CONTENT_TYPE  # TODO: add 'cert_type 'argument
        response = self.net.post(
            authzrs[0].new_cert_uri,  # TODO: acme-spec #90
            req,
            content_type=content_type,
            headers={'Accept': content_type})

        cert_chain_uri = response.links.get('up', {}).get('url')

        try:
            uri = response.headers['Location']
        except KeyError:
            raise errors.ClientError('"Location" Header missing')

        return messages.CertificateResource(
github devopsftw / vergilius / src / vergilius / cert.py View on Github external
def request_certificate(self, csr, authzrs):
        """request certificates for solved challenges"""
        try:
            response = self._acme.request_issuance(jose.util.ComparableX509(csr), authzrs)
            cert_data = HTTPClient().fetch(response.uri).body
            cert = x509.load_der_x509_certificate(cert_data, default_backend())
            return cert
        except messages.Error as error:
            print("This script is doomed to fail as no authorization "
                  "challenges are ever solved. Error from server: {0}".format(error))
        return None
github certbot / certbot / letsencrypt / auth_handler.py View on Github external
"""Returns tuple of ('completed', 'failed')."""
        completed = []
        failed = []

        self.authzr[domain], _ = self.acme.poll(self.authzr[domain])
        if self.authzr[domain].body.status == messages.STATUS_VALID:
            return achalls, []

        # Note: if the whole authorization is invalid, the individual failed
        #     challenges will be determined here...
        for achall in achalls:
            updated_achall = achall.update(challb=self._find_updated_challb(
                self.authzr[domain], achall))

            # This does nothing for challenges that have yet to be decided yet.
            if updated_achall.status == messages.STATUS_VALID:
                completed.append((achall, updated_achall))
            elif updated_achall.status == messages.STATUS_INVALID:
                failed.append((achall, updated_achall))

        return completed, failed
github certbot / certbot / examples / restified.py View on Github external
NEW_REG_URL = 'https://www.letsencrypt-demo.org/acme/new-reg'

key = jose.JWKRSA.load(pkg_resources.resource_string(
    'acme.jose', os.path.join('testdata', 'rsa512_key.pem')))
net = network.Network(NEW_REG_URL, key)

regr = net.register(contact=(
    'mailto:cert-admin@example.com', 'tel:+12025551212'))
logging.info('Auto-accepting TOS: %s', regr.terms_of_service)
net.update_registration(regr.update(
    body=regr.body.update(agreement=regr.terms_of_service)))
logging.debug(regr)

authzr = net.request_challenges(
    identifier=messages.Identifier(
        typ=messages.IDENTIFIER_FQDN, value='example1.com'),
    new_authzr_uri=regr.new_authzr_uri)
logging.debug(authzr)

authzr, authzr_response = net.poll(authzr)

csr = M2Crypto.X509.load_request_string(pkg_resources.resource_string(
    'letsencrypt.tests', os.path.join('testdata', 'csr.pem')))
try:
    net.request_issuance(csr, (authzr,))
except messages.Error as error:
    print error.detail
github kiddouk / letslambda / letslambda.py View on Github external
def register_new_account(conf, key):
    """
    Attempt to create a new account on the ACME server
    with the key. No problem if it fails because this
    kye is already used.
    """
    LOG.info("Registering with ACME server with the new account key")
    newReg = messages.NewRegistration(contact=tuple(conf['info']), key=key.public_key())
    acme_client = client.Client(conf['directory'], key)
    registration_resource = acme_client.register(newReg)
    LOG.info("Agreeing on the TOS on your behalf")
    acme_client.agree_to_tos(registration_resource)
github certbot / certbot / certbot / certbot / _internal / auth_handler.py View on Github external
def _generate_failed_chall_msg(failed_achalls):
    """Creates a user friendly error message about failed challenges.

    :param list failed_achalls: A list of failed
        :class:`certbot.achallenges.AnnotatedChallenge` with the same error
        type.

    :returns: A formatted error message for the client.
    :rtype: str

    """
    error = failed_achalls[0].error
    typ = error.typ
    if messages.is_acme_error(error):
        typ = error.code
    msg = ["The following errors were reported by the server:"]

    for achall in failed_achalls:
        msg.append("\n\nDomain: %s\nType:   %s\nDetail: %s" % (
            achall.domain, typ, achall.error.detail))

    if typ in _ERROR_HELP:
        msg.append("\n\n")
        msg.append(_ERROR_HELP[typ])

    return "".join(msg)