示例#1
0
def perform_registration(
        acme: acme_client.ClientV2, config: configuration.NamespaceConfig,
        tos_cb: Optional[Callable[[str],
                                  None]]) -> messages.RegistrationResource:
    """
    Actually register new account, trying repeatedly if there are email
    problems

    :param acme.client.Client acme: ACME client object.
    :param certbot.configuration.NamespaceConfig config: Client configuration.
    :param Callable tos_cb: a callback to handle Term of Service agreement.

    :returns: Registration Resource.
    :rtype: `acme.messages.RegistrationResource`
    """

    eab_credentials_supplied = config.eab_kid and config.eab_hmac_key
    eab: Optional[Dict[str, Any]]
    if eab_credentials_supplied:
        account_public_key = acme.net.key.public_key()
        eab = messages.ExternalAccountBinding.from_data(
            account_public_key=account_public_key,
            kid=config.eab_kid,
            hmac_key=config.eab_hmac_key,
            directory=acme.directory)
    else:
        eab = None

    if acme.external_account_required():
        if not eab_credentials_supplied:
            msg = ("Server requires external account binding."
                   " Please use --eab-kid and --eab-hmac-key.")
            raise errors.Error(msg)

    try:
        newreg = messages.NewRegistration.from_data(
            email=config.email, external_account_binding=eab)
        # Until ACME v1 support is removed from Certbot, we actually need the provided
        # ACME client to be a wrapper of type BackwardsCompatibleClientV2.
        # TODO: Remove this cast and rewrite the logic when the client is actually a ClientV2
        try:
            return cast(acme_client.BackwardsCompatibleClientV2,
                        acme).new_account_and_tos(newreg, tos_cb)
        except AttributeError:
            raise errors.Error("The ACME client must be an instance of "
                               "acme.client.BackwardsCompatibleClientV2")
    except messages.Error as e:
        if e.code in ("invalidEmail", "invalidContact"):
            if config.noninteractive_mode:
                msg = (
                    "The ACME server believes %s is an invalid email address. "
                    "Please ensure it is a valid email and attempt "
                    "registration again." % config.email)
                raise errors.Error(msg)
            config.email = display_ops.get_email(invalid=True)
            return perform_registration(acme, config, tos_cb)
        raise
示例#2
0
def register(
    config: configuration.NamespaceConfig,
    account_storage: AccountStorage,
    tos_cb: Optional[Callable[[str], None]] = None
) -> Tuple[account.Account, acme_client.ClientV2]:
    """Register new account with an ACME CA.

    This function takes care of generating fresh private key,
    registering the account, optionally accepting CA Terms of Service
    and finally saving the account. It should be called prior to
    initialization of `Client`, unless account has already been created.

    :param certbot.configuration.NamespaceConfig config: Client configuration.

    :param .AccountStorage account_storage: Account storage where newly
        registered account will be saved to. Save happens only after TOS
        acceptance step, so any account private keys or
        `.RegistrationResource` will not be persisted if `tos_cb`
        returns ``False``.

    :param tos_cb: If ACME CA requires the user to accept a Terms of
        Service before registering account, client action is
        necessary. For example, a CLI tool would prompt the user
        acceptance. `tos_cb` must be a callable that should accept
        a Term of Service URL as a string, and raise an exception
        if the TOS is not accepted by the client. ``tos_cb`` will be
        called only if the client action is necessary, i.e. when
        ``terms_of_service is not None``. This argument is optional,
        if not supplied it will default to automatic acceptance!

    :raises certbot.errors.Error: In case of any client problems, in
        particular registration failure, or unaccepted Terms of Service.
    :raises acme.errors.Error: In case of any protocol problems.

    :returns: Newly registered and saved account, as well as protocol
        API handle (should be used in `Client` initialization).
    :rtype: `tuple` of `.Account` and `acme.client.Client`

    """
    # Log non-standard actions, potentially wrong API calls
    if account_storage.find_all():
        logger.info("There are already existing accounts for %s",
                    config.server)
    if config.email is None:
        if not config.register_unsafely_without_email:
            msg = ("No email was provided and "
                   "--register-unsafely-without-email was not present.")
            logger.error(msg)
            raise errors.Error(msg)
        if not config.dry_run:
            logger.debug("Registering without email!")

    # If --dry-run is used, and there is no staging account, create one with no email.
    if config.dry_run:
        config.email = None

    # Each new registration shall use a fresh new key
    rsa_key = generate_private_key(public_exponent=65537,
                                   key_size=config.rsa_key_size,
                                   backend=default_backend())
    key = jose.JWKRSA(key=jose.ComparableRSAKey(rsa_key))
    acme = acme_from_config_key(config, key)
    # TODO: add phone?
    regr = perform_registration(acme, config, tos_cb)

    acc = account.Account(regr, key)
    account_storage.save(acc, acme)

    eff.prepare_subscription(config, acc)

    return acc, acme