org.shredzone.acme4j.exception.AcmeException Java Examples

The following examples show how to use org.shredzone.acme4j.exception.AcmeException. 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: AcmeClient.java    From r2cloud with Apache License 2.0 6 votes vote down vote up
private Registration loadOrRegisterAccount(Session session) throws AcmeException {
	Registration reg;
	try {
		messages.add("registering new user", LOG);
		reg = new RegistrationBuilder().create(session);
		URI agreement = reg.getAgreement();
		messages.add("accepting terms of service", LOG);

		EditableRegistration editableReg = reg.modify();
		editableReg.setAgreement(agreement);
		editableReg.addContact("mailto:" + config.getProperty("server.login"));
		editableReg.commit();
	} catch (AcmeConflictException ex) {
		messages.add("account already exists. use it", LOG);
		reg = Registration.bind(session, ex.getLocation());
	}
	return reg;
}
 
Example #2
Source File: AddEmailCommand.java    From acme_client with MIT License 6 votes vote down vote up
@Override
public void commandExecution() {
    try {
        boolean emailExists = false;
        URI emailURI = new URI(MAILTO_SCHEME+getParameters().getEmail());

        for(URI contact : registrationManagement.getAccount().getContacts()){
            if (emailURI.equals(contact)){
                emailExists = true;
                break;
            }
        }

        if(!emailExists){
            registrationManagement.addContact(emailURI);
        }

    } catch (AcmeException | URISyntaxException e) {
        LOG.error("Cannot add email : "+getParameters().getEmail(), e);
        error = true;
    }
}
 
Example #3
Source File: IOManager.java    From acme_client with MIT License 6 votes vote down vote up
public static X509Certificate[] readX509Certificates(String path) throws IOException, CertificateException, AcmeException {
    try (FileInputStream fis = new FileInputStream(path)) {

        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        Collection c = cf.generateCertificates(fis);
        Iterator it = c.iterator();
        ArrayList<X509Certificate> certificates = new ArrayList<>();

        while (it.hasNext()) {
            Certificate cert = (Certificate) it.next();
            CertificateFactory certFact = CertificateFactory.getInstance("X.509");
            certificates.add((X509Certificate) certFact.generateCertificate(new ByteArrayInputStream(cert.getEncoded())));
        }

        X509Certificate[] x509Certificates = new X509Certificate[certificates.size()];

        for (int i = 0; i < x509Certificates.length; i++) {
            x509Certificates[i] = certificates.get(i);
        }

        return x509Certificates;
    }
}
 
Example #4
Source File: CertGenerator.java    From spring-boot-starter-acme with Apache License 2.0 6 votes vote down vote up
/**
 * Finds your {@link Registration} at the ACME server. It will be found by your user's
 * public key. If your key is not known to the server yet, a new registration will be
 * created.
 * <p>
 * This is a simple way of finding your {@link Registration}. A better way is to get
 * the URL of your new registration with {@link Registration#getLocation()} and store
 * it somewhere. If you need to get access to your account later, reconnect to it via
 * {@link Registration#bind(Session, URL)} by using the stored location.
 *
 * @param session
 *            {@link Session} to bind with
 * @return {@link Registration} connected to your account
 */
private Registration getOrCreateAccount(Session session) throws AcmeException {

  Registration reg;

  try {
    // Try to create a new Registration.
    reg = new RegistrationBuilder().create(session);
    logger.info("Registered a new user, URL: " + reg.getLocation());

    // This is a new account. Let the user accept the Terms of Service.
    // We won't be able to authorize domains until the ToS is accepted.
    URI agreement = reg.getAgreement();
    logger.info("Terms of Service: " + agreement);
    acceptAgreement(reg, agreement);

  } catch (AcmeConflictException ex) {
    // The Key Pair is already registered. getLocation() contains the
    // URL of the existing registration's location. Bind it to the session.
    reg = Registration.bind(session, ex.getLocation());
    logger.info("Account does already exist, URL: " + reg.getLocation(), ex);
  }

  return reg;
}
 
Example #5
Source File: AccountManager.java    From acme_client with MIT License 5 votes vote down vote up
public AccountManager(KeyPair keyPair, Session session, String keyIdentifier,
                      SecretKey macKey, boolean agreeToTermsOfService)
        throws AcmeException {
    AccountBuilder accountBuilder = new AccountBuilder()
            .withKeyIdentifier(keyIdentifier, macKey).useKeyPair(keyPair);
    if(agreeToTermsOfService){
        accountBuilder = accountBuilder.agreeToTermsOfService();
    }
    this.login = accountBuilder.createLogin(session);
    this.account = this.login.getAccount();
}
 
Example #6
Source File: AcmeClient.java    From blynk-server with GNU General Public License v3.0 5 votes vote down vote up
private Http01Challenge httpChallenge(Authorization auth) throws AcmeException {
    // Find a single http-01 challenge
    Http01Challenge challenge = auth.findChallenge(Http01Challenge.TYPE);
    if (challenge == null) {
        throw new AcmeException("Found no " + Http01Challenge.TYPE + " challenge, don't know what to do...");
    }

    // Output the challenge, wait for acknowledge...
    log.debug("http://{}/.well-known/acme-challenge/{}", auth.getIdentifier().getDomain(), challenge.getToken());
    log.debug("Content: {}", challenge.getAuthorization());

    return challenge;
}
 
Example #7
Source File: LetsEncryptReloadLifecycle.java    From openwebbeans-meecrowave with Apache License 2.0 5 votes vote down vote up
private Challenge httpChallenge(final Authorization auth) throws AcmeException {
    final Http01Challenge challenge = auth.findChallenge(Http01Challenge.TYPE);
    if (challenge == null) {
        throw new AcmeException("Challenge is null");
    }

    challengeUpdater.accept("/.well-known/acme-challenge/" + challenge.getToken(), challenge.getAuthorization());
    return challenge;
}
 
Example #8
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 #9
Source File: DeactivateAccountCommand.java    From acme_client with MIT License 5 votes vote down vote up
@Override
public void commandExecution() {
    try {
        registrationManagement.deactivateAccount();
    } catch (AcmeException e) {
        LOG.error("Cannot deactivate account", e);
        error = true;
    }
}
 
Example #10
Source File: AuthorizationManager.java    From acme_client with MIT License 5 votes vote down vote up
public boolean authorizeDomain() throws AcmeException{
    return ValidationService.validate(new ResourceWithStatusWrapper() {
        @Override
        public Status getStatus() {
            return authorization.getStatus();
        }

        @Override
        public void trigger() throws AcmeException {
        }

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

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

        @Override
        public void failIfInvalid() throws AcmeException {
            if(isAuthorizationUnusable()){
                throw new AcmeException("Authorization: "+authorization.getLocation().toString()+" cannot be used " +
                        "anymore");
            }
        }

        private boolean isAuthorizationUnusable(){
            return authorization.getStatus() == Status.INVALID ||
                    authorization.getStatus() == Status.EXPIRED ||
                    authorization.getStatus() == Status.DEACTIVATED ||
                    authorization.getStatus() == Status.REVOKED;
        }
    });
}
 
Example #11
Source File: AccountManager.java    From acme_client with MIT License 5 votes vote down vote up
public void deactivateAccount() throws AcmeException {
    try {
        this.account.deactivate();
    } catch (AcmeException e) {
        if (!e.getMessage().equals("HTTP 202: Accepted")) {
            throw e;
        }
    }
}
 
Example #12
Source File: AccountManager.java    From acme_client with MIT License 5 votes vote down vote up
public AccountManager(KeyPair keyPair, Session session, String keyIdentifier,
                      String macKey, boolean agreeToTermsOfService)
        throws AcmeException {
    AccountBuilder accountBuilder = new AccountBuilder()
            .withKeyIdentifier(keyIdentifier, macKey).useKeyPair(keyPair);
    if(agreeToTermsOfService){
        accountBuilder = accountBuilder.agreeToTermsOfService();
    }
    this.login = accountBuilder.createLogin(session);
    this.account = this.login.getAccount();
}
 
Example #13
Source File: AccountManager.java    From acme_client with MIT License 5 votes vote down vote up
public AccountManager(KeyPair keyPair, Session session, boolean agreeToTermsOfService)
        throws AcmeException {
    AccountBuilder accountBuilder = new AccountBuilder().useKeyPair(keyPair);
    if(agreeToTermsOfService){
        accountBuilder = accountBuilder.agreeToTermsOfService();
    }
    this.login = accountBuilder.createLogin(session);
    this.account = this.login.getAccount();
}
 
Example #14
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 #15
Source File: ChallengeManager.java    From acme_client with MIT License 5 votes vote down vote up
public ChallengeManager(Authorization authorization, String type, Login login) throws AcmeException {
    this.challenge = authorization.findChallenge(type);
    if (this.challenge == null) throw new AcmeException();
    try {
        challenge.rebind(login);
    } catch (Exception ex) {
        LOG.warn("Can not rebind challenge: " + challenge.getLocation() + " to login: " +
                login.getAccountLocation().toString(), ex);
    }
}
 
Example #16
Source File: ChallengeManager.java    From acme_client with MIT License 5 votes vote down vote up
public ChallengeManager(Challenge challenge, Login login) throws AcmeException {
    this.challenge = challenge;
    try {
        challenge.rebind(login);
    } catch (Exception ex) {
        LOG.warn("Cannot rebind challenge: " + challenge.getLocation() + " to login: " +
                login.getAccountLocation().toString(), ex);
    }
}
 
Example #17
Source File: OrderManager.java    From acme_client with MIT License 5 votes vote down vote up
public OrderManager(Account account, Set<String> domainNames, OrderInstants orderInstants) throws AcmeException {
    OrderBuilder orderBuilder = account.newOrder().domains(domainNames);
    if(orderInstants.getNotAfter().isPresent()){
        orderBuilder = orderBuilder.notAfter(orderInstants.getNotAfter().get());
    }
    if(orderInstants.getNotBefore().isPresent()){
        orderBuilder = orderBuilder.notBefore(orderInstants.getNotBefore().get());
    }
    this.order = orderBuilder.create();
}
 
Example #18
Source File: OrderManager.java    From acme_client with MIT License 5 votes vote down vote up
public boolean validateOrder() throws AcmeException{
    return ValidationService.validate(new ResourceWithStatusWrapper() {
        @Override
        public Status getStatus() {
            return order.getStatus();
        }

        @Override
        public void trigger() throws AcmeException {

        }

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

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

        @Override
        public void failIfInvalid() throws AcmeException {
            if (order.getStatus() == Status.INVALID) {
                throw new AcmeException("Order invalid: "+getLocation());
            }
            if (order.getStatus() == Status.PENDING) {
                throw new AcmeException("Not all authorizations was completed for order to be validated: "+
                        getLocation());
            }
        }
    });
}
 
Example #19
Source File: CertificateManager.java    From acme_client with MIT License 5 votes vote down vote up
public boolean revokeCertificate(X509Certificate x509Certificate, int leftSeconds) throws AcmeException {
    if ((System.currentTimeMillis() + leftSeconds) >= x509Certificate.getNotAfter().getTime()) {
        this.certificate.revoke();
        return true;
    }
    return false;
}
 
Example #20
Source File: CertificateManager.java    From acme_client with MIT License 5 votes vote down vote up
public boolean revokeCertificate(int leftSeconds) throws AcmeException {
    if ((System.currentTimeMillis() + leftSeconds) >= this.certificate.getCertificate().getNotAfter().getTime()) {
        this.certificate.revoke();
        return true;
    }
    return false;
}
 
Example #21
Source File: DownloadChallengesCommand.java    From acme_client with MIT License 4 votes vote down vote up
public DownloadChallengesCommand(Parameters parameters) throws AccountKeyNotFoundException, AcmeException {
    super(parameters);
}
 
Example #22
Source File: GenerateCertificateCommand.java    From acme_client with MIT License 4 votes vote down vote up
public GenerateCertificateCommand(Parameters parameters)
        throws AccountKeyNotFoundException, AcmeException {
    super(parameters);
}
 
Example #23
Source File: DownloadCertificatesCommand.java    From acme_client with MIT License 4 votes vote down vote up
public DownloadCertificatesCommand(Parameters parameters) throws AccountKeyNotFoundException, AcmeException {
    super(parameters);
}
 
Example #24
Source File: DeactivateDomainsOrderCommand.java    From acme_client with MIT License 4 votes vote down vote up
public DeactivateDomainsOrderCommand(Parameters parameters) throws AccountKeyNotFoundException,
        AcmeException {
    super(parameters);
}
 
Example #25
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 #26
Source File: OrderCertificateCommand.java    From acme_client with MIT License 4 votes vote down vote up
public OrderCertificateCommand(Parameters parameters)
        throws AccountKeyNotFoundException, AcmeException {
    super(parameters);
}
 
Example #27
Source File: CertificateCommand.java    From acme_client with MIT License 4 votes vote down vote up
CertificateCommand(Parameters parameters) throws AccountKeyNotFoundException, AcmeException {
    super(parameters);
    ORDER_FILE_PATH = Paths.get(getParameters().getWorkDir(), Parameters.ORDER_URI_LIST).toString();
    CERTIFICATE_FILE_PATH = Paths.get(getParameters().getWorkDir(), Parameters.CERTIFICATE_URI_LIST).toString();
}
 
Example #28
Source File: VerifyDomainsCommand.java    From acme_client with MIT License 4 votes vote down vote up
public VerifyDomainsCommand(Parameters parameters) throws AccountKeyNotFoundException, AcmeException {
    super(parameters);
}
 
Example #29
Source File: AuthorizedCommand.java    From acme_client with MIT License 4 votes vote down vote up
public AuthorizedCommand(Parameters parameters) throws AccountKeyNotFoundException, AcmeException {
    super(parameters);
    accountManager = new AccountManager(getAccountKey(), getSession(), parameters.isWithAgreementUpdate());
}
 
Example #30
Source File: OrderManager.java    From acme_client with MIT License 4 votes vote down vote up
public OrderManager(Account account, Set<String> domainNames) throws AcmeException {
    this.order = account.newOrder().domains(domainNames).create();
}