How to use the letsencrypt.crypto_util function in letsencrypt

To help you get started, we’ve selected a few letsencrypt 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 certbot / certbot / letsencrypt / cli.py View on Github external
def _auth_from_domains(le_client, config, domains, plugins):
    """Authenticate and enroll certificate."""
    # Note: This can raise errors... caught above us though.
    lineage = _treat_as_renewal(config, domains)

    if lineage is not None:
        # TODO: schoen wishes to reuse key - discussion
        # https://github.com/letsencrypt/letsencrypt/pull/777/files#r40498574
        new_certr, new_chain, new_key, _ = le_client.obtain_certificate(domains)
        # TODO: Check whether it worked! <- or make sure errors are thrown (jdk)
        lineage.save_successor(
            lineage.latest_common_version(), OpenSSL.crypto.dump_certificate(
                OpenSSL.crypto.FILETYPE_PEM, new_certr.body),
            new_key.pem, crypto_util.dump_pyopenssl_chain(new_chain))

        lineage.update_all_links_to(lineage.latest_common_version())
        # TODO: Check return value of save_successor
        # TODO: Also update lineage renewal config with any relevant
        #       configuration values from this attempt? <- Absolutely (jdkasten)
    else:
        # TREAT AS NEW REQUEST
        lineage = le_client.obtain_and_enroll_certificate(domains, plugins)
        if not lineage:
            raise errors.Error("Certificate could not be obtained")

    _report_new_cert(lineage.cert)

    return lineage
github certbot / certbot / letsencrypt / client.py View on Github external
def obtain_certificate(self, domains):
        """Obtains a certificate from the ACME server.

        `.register` must be called before `.obtain_certificate`

        :param list domains: domains to get a certificate

        :returns: `.CertificateResource`, certificate chain (as
            returned by `.fetch_chain`), and newly generated private key
            (`.le_util.Key`) and DER-encoded Certificate Signing Request
            (`.le_util.CSR`).
        :rtype: tuple

        """
        # Create CSR from names
        key = crypto_util.init_save_key(
            self.config.rsa_key_size, self.config.key_dir)
        csr = crypto_util.init_save_csr(key, domains, self.config.csr_dir)

        return self._obtain_certificate(domains, csr) + (key, csr)
github certbot / certbot / letsencrypt / storage.py View on Github external
most current cert version in this lineage
        :rtype: bool

        """
        if interactive or self.autorenewal_is_enabled():
            # Consider whether to attempt to autorenew this cert now

            # Renewals on the basis of revocation
            if self.ocsp_revoked(self.latest_common_version()):
                logger.debug("Should renew, certificate is revoked.")
                return True

            # Renews some period before expiry time
            default_interval = constants.RENEWER_DEFAULTS["renew_before_expiry"]
            interval = self.configuration.get("renew_before_expiry", default_interval)
            expiry = crypto_util.notAfter(self.version(
                "cert", self.latest_common_version()))
            now = pytz.UTC.fromutc(datetime.datetime.utcnow())
            if expiry < add_time_interval(now, interval):
                logger.debug("Should renew, less than %s before certificate "
                             "expiry %s.", interval,
                             expiry.strftime("%Y-%m-%d %H:%M:%S %Z"))
                return True
        return False
github certbot / certbot / letsencrypt / cert_manager.py View on Github external
:returns: map from cert sha1 fingerprint to :class:`list` of vhosts
            where the certificate is installed.

        """
        csha1_vhlist = {}

        for installer in self.installers:
            for (cert_path, _, path) in installer.get_all_certs_keys():
                try:
                    with open(cert_path) as cert_file:
                        cert_data = cert_file.read()
                except IOError:
                    continue
                try:
                    cert_obj, _ = crypto_util.pyopenssl_load_certificate(
                        cert_data)
                except errors.Error:
                    continue
                cert_sha1 = cert_obj.digest("sha1")
                if cert_sha1 in csha1_vhlist:
                    csha1_vhlist[cert_sha1].append(path)
                else:
                    csha1_vhlist[cert_sha1] = [path]

        return csha1_vhlist
github certbot / certbot / letsencrypt / renewer.py View on Github external
account_id=renewalparams["account"])

    le_client = client.Client(config, acc, authenticator, None)
    with open(cert.version("cert", old_version)) as f:
        sans = crypto_util.get_sans_from_cert(f.read())
    new_certr, new_chain, new_key, _ = le_client.obtain_certificate(sans)
    if new_chain:
        # XXX: Assumes that there was a key change.  We need logic
        #      for figuring out whether there was or not.  Probably
        #      best is to have obtain_certificate return None for
        #      new_key if the old key is to be used (since save_successor
        #      already understands this distinction!)
        return cert.save_successor(
            old_version, OpenSSL.crypto.dump_certificate(
                OpenSSL.crypto.FILETYPE_PEM, new_certr.body),
            new_key.pem, crypto_util.dump_pyopenssl_chain(new_chain))
        # TODO: Notify results
    else:
        # TODO: Notify negative results
        return False
    # TODO: Consider the case where the renewal was partially successful
github certbot / certbot / letsencrypt / revoker.py View on Github external
def __str__(self):
        text = [
            "Subject: %s" % crypto_util.pyopenssl_x509_name_as_text(
                self._cert.get_subject()),
            "SAN: %s" % self.get_san(),
            "Issuer: %s" % crypto_util.pyopenssl_x509_name_as_text(
                self._cert.get_issuer()),
            "Public Key: %s" % self.get_pub_key(),
            "Not Before: %s" % str(self.get_not_before()),
            "Not After: %s" % str(self.get_not_after()),
            "Serial Number: %s" % self._cert.get_serial_number(),
            "SHA1: %s%s" % (self.get_fingerprint(), os.linesep),
            "Installed: %s" % ", ".join(self.installed),
        ]

        if self.orig is not None:
            if self.orig.status == "":
                text.append("Path: %s" % self.orig.path)
            else:
github certbot / certbot / letsencrypt / cert_manager.py View on Github external
def success_revocation(cert, version=None):
    """Display a success message.

    :param cert: cert that was revoked
    :type cert: :class:`letsencrypt.storage.RenewableCert`

    :param int version: Version if only revoking a single cert in the lineage.

    """
    if version is None:
        msg = "You have successfully revoked all the certificates in this " \
              "lineage. (%d)" % len(cert.available_versions("cert"))
    else:
        msg = "You have successfully revoked the certificate for "
        "%s" % " ".join(
            crypto_util.get_sans_from_pyopenssl(cert.pyopenssl(version)))

    zope.component.getUtility(interfaces.IDisplay).notification(msg)
github certbot / certbot / letsencrypt / plugins / standalone / authenticator.py View on Github external
def __init__(self, *args, **kwargs):
        super(StandaloneAuthenticator, self).__init__(*args, **kwargs)
        self.child_pid = None
        self.parent_pid = os.getpid()
        self.subproc_state = None
        self.tasks = {}
        self.sni_names = {}
        self.sock = None
        self.connection = None
        self.key_pem = crypto_util.make_key(bits=2048)
        self.private_key = OpenSSL.crypto.load_privatekey(
            OpenSSL.crypto.FILETYPE_PEM, self.key_pem)
        self.ssl_conn = None
github certbot / certbot / letsencrypt / storage.py View on Github external
been reached.)

        :param bool interactive: set to True to examine the question
            regardless of whether the renewal configuration allows
            automated deployment (for interactive use). Default False.

        :returns: whether the lineage now ought to autodeploy an
            existing newer cert version
        :rtype: bool

        """
        if interactive or self.autodeployment_is_enabled():
            if self.has_pending_deployment():
                interval = self.configuration.get("deploy_before_expiry",
                                                  "5 days")
                expiry = crypto_util.notAfter(self.current_target("cert"))
                now = pytz.UTC.fromutc(datetime.datetime.utcnow())
                if expiry < add_time_interval(now, interval):
                    return True
        return False