org.shredzone.acme4j.Status Java Examples

The following examples show how to use org.shredzone.acme4j.Status. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ChallengeManager.java    From acme_client with MIT License 5 votes vote down vote up
public boolean validateChallenge() throws AcmeException {
    return ValidationService.validate(new ResourceWithStatusWrapper() {
        @Override
        public Status getStatus() {
            return challenge.getStatus();
        }

        @Override
        public void trigger() throws AcmeException {
            challenge.trigger();
        }

        @Override
        public void update() throws AcmeException {
            challenge.update();
        }

        @Override
        public String getLocation() {
            return challenge.getLocation().toString();
        }

        @Override
        public void failIfInvalid() throws AcmeException {
            if (challenge.getStatus() == Status.INVALID) {
                throw new AcmeException("Challenge invalid: "+getLocation());
            }
        }
    });
}
 
Example #2
Source File: CertificateCommand.java    From acme_client with MIT License 5 votes vote down vote up
void writeChallengeByAuthorization(AuthorizationManager authorizationManagement) throws Exception {
    switch (getChallengeType()) {
        case Http01Challenge.TYPE:
            Http01Challenge http01Challenge = authorizationManagement.getHttp01Challenge();
            if(http01Challenge.getStatus()== Status.INVALID){
                throw new ChallengeInvalidException(http01Challenge.getLocation().toString());
            }
            String path;
            if (getParameters().isOneDirForWellKnown()) {
                path = Paths.get(getParameters().getWellKnownDir(), http01Challenge.getToken()).toString();
            } else {
                String subdir = authorizationManagement.getAuthorization().getIdentifier().getDomain()+
                        returnIfWildcard(authorizationManagement.getAuthorization());
                path = Paths.get(getParameters().getWellKnownDir(), subdir).toString();
                IOManager.createDirectories(path);
                path = Paths.get(path, http01Challenge.getToken()).toString();
            }
            IOManager.writeString(path, http01Challenge.getAuthorization());
            break;
        case Dns01Challenge.TYPE:
            Dns01Challenge dns01Challenge = authorizationManagement.getDns01Challenge();
            if(dns01Challenge.getStatus()== Status.INVALID){
                throw new ChallengeInvalidException(dns01Challenge.getLocation().toString());
            }
            Authorization authorization = authorizationManagement.getAuthorization();
            String fileSuffix = "_dns_digest"+returnIfWildcard(authorization);
            IOManager.writeString(
                    Paths.get(getParameters().getDnsDigestDir(),
                            authorizationManagement.getAuthorization().getIdentifier().getDomain() + fileSuffix).toString(),
                    dns01Challenge.getDigest()
            );
            break;
    }
}
 
Example #3
Source File: LetsEncryptReloadLifecycle.java    From openwebbeans-meecrowave with Apache License 2.0 5 votes vote down vote up
private boolean authorize(final Authorization authorization) throws AcmeException {
    final Challenge challenge = httpChallenge(authorization);
    if (challenge == null) {
        throw new AcmeException("HTTP challenge is null");
    }
    if (challenge.getStatus() == Status.VALID) {
        return false;
    }

    challenge.trigger();

    try {
        int attempts = config.getRetryCount();
        while (challenge.getStatus() != Status.VALID && attempts-- > 0) {
            if (challenge.getStatus() == Status.INVALID) {
                throw new AcmeException("Invalid challenge status, exiting refresh iteration");
            }

            Thread.sleep(config.getRetryTimeoutMs());
            challenge.update();
        }
    } catch (final InterruptedException ex) {
        Thread.currentThread().interrupt();
    }

    if (challenge.getStatus() != Status.VALID) {
        throw new AcmeException("Challenge for domain " + authorization.getDomain() + ", is invalid, exiting iteration");
    }
    return true;
}
 
Example #4
Source File: CertGenerator.java    From spring-boot-starter-acme with Apache License 2.0 4 votes vote down vote up
/**
 * Authorize a domain. It will be associated with your account, so you will be able to
 * retrieve a signed certificate for the domain later.
 * <p>
 * You need separate authorizations for subdomains (e.g. "www" subdomain). Wildcard
 * certificates are currently not supported.
 *
 * @param aRegistration
 *            {@link Registration} of your account
 * @param aDomain
 *            Name of the domain to authorize
 */
private void authorize (Registration aRegistration, String aDomain) throws AcmeException {
  // Authorize the domain.
  Authorization auth = aRegistration.authorizeDomain(aDomain);
  logger.info("Authorization for domain " + aDomain);

  // Find the desired challenge and prepare it.
  Challenge challenge = httpChallenge(auth, aDomain);

  // If the challenge is already verified, there's no need to execute it again.
  if (challenge.getStatus() == Status.VALID) {
    return;
  }

  // Now trigger the challenge.
  challenge.trigger();

  // Poll for the challenge to complete.
  try {
    int attempts = 10;
    while (challenge.getStatus() != Status.VALID && attempts-- > 0) {
      // Did the authorization fail?
      if (challenge.getStatus() == Status.INVALID) {
        throw new AcmeException("Challenge failed... Giving up.");
      }

      // Wait for a few seconds
      Thread.sleep(3000L);

      // Then update the status
      challenge.update();
    }
  } catch (InterruptedException ex) {
    logger.error("interrupted", ex);
  }

  // All reattempts are used up and there is still no valid authorization?
  if (challenge.getStatus() != Status.VALID) {
    throw new AcmeException("Failed to pass the challenge for domain " + aDomain + ", ... Giving up.");
  }
  
}
 
Example #5
Source File: AcmeClient.java    From r2cloud with Apache License 2.0 4 votes vote down vote up
private void authorize(Registration reg, String domain) throws AcmeException, IOException {
	messages.add("authorizing domain: " + domain, LOG);
	Authorization auth = reg.authorizeDomain(domain);
	messages.add("find http challenge", LOG);
	Http01Challenge challenge1 = auth.findChallenge(Http01Challenge.TYPE);
	if (challenge1 == null) {
		throw new AcmeException("Found no " + Http01Challenge.TYPE + " challenge, don't know what to do...");
	}
	messages.add("saving challenge request", LOG);
	try (FileOutputStream fos = new FileOutputStream(new File(challengePath, challenge1.getToken()))) {
		fos.write(challenge1.getAuthorization().getBytes(StandardCharsets.UTF_8));
	}

	Challenge challenge = challenge1;
	if (challenge.getStatus() == Status.VALID) {
		messages.add("challenge already successeded", LOG);
		return;
	}
	messages.add("trigger challenge", LOG);
	challenge.trigger();

	// Poll for the challenge to complete.
	long retryTimeout = INITIAL_RETRY;
	while (challenge.getStatus() != Status.VALID && !Thread.currentThread().isInterrupted()) {
		// Did the authorization fail?
		if (challenge.getStatus() == Status.INVALID) {
			messages.add("Authorization failed: " + challenge.getError().getDetail());
			throw new AcmeException("Challenge failed...");
		}

		try {
			Thread.sleep(retryTimeout);
		} catch (InterruptedException ex) {
			Thread.currentThread().interrupt();
			break;
		}

		try {
			messages.add("update challenge", LOG);
			challenge.update();
		} catch (AcmeRetryAfterException e) {
			retryTimeout = e.getRetryAfter().toEpochMilli() - System.currentTimeMillis();
			messages.add("not ready. retry after: " + retryTimeout + " millis", LOG);
		}
	}

	// All reattempts are used up and there is still no valid authorization?
	if (challenge.getStatus() != Status.VALID) {
		throw new AcmeException("Failed to pass the challenge for domain " + domain + ", ... Giving up.");
	}
}
 
Example #6
Source File: DeactivateDomainsOrderCommand.java    From acme_client with MIT License 4 votes vote down vote up
@Override
public void commandExecution() {

    List<Order> orders = getNotExpiredOrders();
    if (orders == null) {
        LOG.error("Cannot read file: " + ORDER_FILE_PATH);
        error = true;
        return;
    }

    List<String> failedAuthorizations = new LinkedList<>();

    List<Order> newOrderList = new LinkedList<>();

    Set<String> domains = retrieveDomainsFromParametersOrCSR();

    if(error){
        LOG.error("Domains retrieval failed");
        return;
    }

    for(Order order : orders) {
        boolean deactivated = false;
        for (Authorization authorization : order.getAuthorizations()) {
            String domain = getDomain(authorization);
            if (domains == null || domains.contains(domain)) {
                try {
                    if(!authorization.getStatus().equals(Status.DEACTIVATED)) {
                        authorization.deactivate();
                    }
                    deactivated = true;
                } catch (AcmeException e) {
                    LOG.error("Cannot deactivate authorization: " + authorization.getLocation().toString(), e);
                    failedAuthorizations.add(authorization.getLocation().toString());
                }
            }
        }
        if(!deactivated){
            newOrderList.add(order);
        }
    }

    error = error || !writeOrderList(newOrderList);

    if (failedAuthorizations.size() > 0) {
        JsonElement failedDomainsJsonElement = getGson().toJsonTree(failedAuthorizations, new TypeToken<List<String>>() {
        }.getType());
        result.add("failed_authorizations", failedDomainsJsonElement);
        error=true;
    }
}
 
Example #7
Source File: AcmeClient.java    From blynk-server with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Generates a certificate for the given domains. Also takes care for the registration
 * process.
 *
 * @param domain
 *            Domains to get a common certificate for
 */
private void fetchCertificate(String contact, String domain) throws IOException, AcmeException {
    // Load the user key file. If there is no key file, create a new one.
    // Keep this key pair in a safe place! In a production environment, you will not be
    // able to access your account again if you should lose the key pair.
    KeyPair userKeyPair = loadOrCreateKeyPair(USER_KEY_FILE);

    Session session = new Session(letsEncryptUrl);

    // Get the Account.
    // If there is no account yet, create a new one.
    Account account = new AccountBuilder()
            .agreeToTermsOfService()
            .useKeyPair(userKeyPair)
            .addEmail(contact)
            .create(session);
    log.info("Registered a new user, URL: {}", account.getLocation());

    // Load or create a key pair for the domains. This should not be the userKeyPair!
    KeyPair domainKeyPair = loadOrCreateKeyPair(DOMAIN_KEY_FILE);

    // Order the certificate
    Order order = account.newOrder().domain(domain).create();

    // Perform all required authorizations
    for (Authorization auth : order.getAuthorizations()) {
        authorize(auth);
    }

    // Generate a CSR for all of the domains, and sign it with the domain key pair.
    CSRBuilder csrb = new CSRBuilder();
    csrb.addDomain(domain);
    csrb.setOrganization("Blynk Inc.");
    csrb.sign(domainKeyPair);

    // Order the certificate
    order.execute(csrb.getEncoded());

    // Wait for the order to complete
    try {
        int attempts = ATTEMPTS;
        while (order.getStatus() != Status.VALID && attempts-- > 0) {
            if (order.getStatus() == Status.INVALID) {
                throw new AcmeException("Order failed... Giving up.");
            }
            Thread.sleep(WAIT_MILLIS);
            order.update();
        }
    } catch (InterruptedException ex) {
        log.error("interrupted", ex);
    }

    Certificate certificate = order.getCertificate();

    if (certificate != null) {
        try (FileWriter fw = new FileWriter(DOMAIN_CHAIN_FILE)) {
            certificate.writeCertificate(fw);
        }
        log.info("Overriding certificate. Expiration date is : {}", certificate.getCertificate().getNotAfter());
    }
}
 
Example #8
Source File: AcmeClient.java    From blynk-server with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Authorize a domain. It will be associated with your account, so you will be able to
 * retrieve a signed certificate for the domain later.
 *
 * @param auth
 *            {@link Authorization} to perform
 */
private void authorize(Authorization auth) throws AcmeException {
    log.info("Starting authorization for domain {}", auth.getIdentifier().getDomain());

    // Find the desired challenge and prepare it.
    Http01Challenge challenge = httpChallenge(auth);

    if (challenge == null) {
        throw new AcmeException("No challenge found");
    }

    contentHolder.content = challenge.getAuthorization();

    // If the challenge is already verified, there's no need to execute it again.
    if (challenge.getStatus() == Status.VALID) {
        return;
    }

    // Now trigger the challenge.
    challenge.trigger();

    // Poll for the challenge to complete.
    try {
        int attempts = ATTEMPTS;
        while (challenge.getStatus() != Status.VALID && attempts-- > 0) {
            if (challenge.getStatus() == Status.INVALID) {
                throw new AcmeException("Challenge failed... Giving up.");
            }
            Thread.sleep(WAIT_MILLIS);
            challenge.update();
        }
    } catch (InterruptedException ex) {
        log.error("interrupted", ex);
        return;
    }

    // All reattempts are used up and there is still no valid authorization?
    if (challenge.getStatus() != Status.VALID) {
        throw new AcmeException("Failed to pass the challenge for domain "
                + auth.getIdentifier().getDomain() + ", ... Giving up.");
    }
}
 
Example #9
Source File: ResourceWithStatusWrapper.java    From acme_client with MIT License votes vote down vote up
Status getStatus();