Search in sources :

Example 1 with Session

use of org.shredzone.acme4j.Session in project meecrowave by apache.

the class LetsEncryptReloadLifecycle method run.

@Override
public synchronized void run() {
    final KeyPair userKeyPair = loadOrCreateKeyPair(config.getUserKeySize(), config.getUserKeyLocation());
    final KeyPair domainKeyPair = loadOrCreateKeyPair(config.getDomainKeySize(), config.getDomainKey());
    final Session session = new Session(config.getEndpoint());
    try {
        final Account account = new AccountBuilder().agreeToTermsOfService().useKeyPair(userKeyPair).create(session);
        final Order order = account.newOrder().domains(config.getDomains().trim().split(",")).create();
        final boolean updated = order.getAuthorizations().stream().map(authorization -> {
            try {
                return authorize(authorization);
            } catch (final AcmeException e) {
                getLogger().error(e.getMessage(), e);
                return false;
            }
        }).reduce(false, (previous, val) -> previous || val);
        if (!updated) {
            return;
        }
        final CSRBuilder csrBuilder = new CSRBuilder();
        csrBuilder.addDomains(config.getDomains());
        csrBuilder.sign(domainKeyPair);
        try (final Writer writer = new BufferedWriter(new FileWriter(config.getDomainCertificate()))) {
            csrBuilder.write(writer);
        }
        order.execute(csrBuilder.getEncoded());
        try {
            int attempts = config.getRetryCount();
            while (order.getStatus() != Status.VALID && attempts-- > 0) {
                if (order.getStatus() == Status.INVALID) {
                    throw new AcmeException("Order failed... Giving up.");
                }
                Thread.sleep(config.getRetryTimeoutMs());
                order.update();
            }
        } catch (final InterruptedException ex) {
            getLogger().error(ex.getMessage());
            Thread.currentThread().interrupt();
            return;
        }
        final Certificate certificate = order.getCertificate();
        getLogger().info("Got new certificate " + certificate.getLocation() + " for domain(s) " + config.getDomains());
        try (final Writer writer = new BufferedWriter(new FileWriter(config.getDomainChain()))) {
            certificate.writeCertificate(writer);
        }
        protocol.reloadSslHostConfigs();
    } catch (final AcmeException | IOException ex) {
        getLogger().error(ex.getMessage(), ex);
    }
}
Also used : Order(org.shredzone.acme4j.Order) AccountBuilder(org.shredzone.acme4j.AccountBuilder) JcaPEMWriter(org.bouncycastle.openssl.jcajce.JcaPEMWriter) KeyPair(java.security.KeyPair) JcaPEMKeyConverter(org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter) Http01Challenge(org.shredzone.acme4j.challenge.Http01Challenge) ScheduledFuture(java.util.concurrent.ScheduledFuture) AbstractHttp11Protocol(org.apache.coyote.http11.AbstractHttp11Protocol) Authorization(org.shredzone.acme4j.Authorization) Certificate(org.shredzone.acme4j.Certificate) AtomicReference(java.util.concurrent.atomic.AtomicReference) Order(org.shredzone.acme4j.Order) Status(org.shredzone.acme4j.Status) Challenge(org.shredzone.acme4j.challenge.Challenge) CSRBuilder(org.shredzone.acme4j.util.CSRBuilder) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) BiConsumer(java.util.function.BiConsumer) ThreadFactory(java.util.concurrent.ThreadFactory) ExecutorService(java.util.concurrent.ExecutorService) KeyPairGenerator(java.security.KeyPairGenerator) LogFacade(org.apache.meecrowave.logging.tomcat.LogFacade) PEMParser(org.bouncycastle.openssl.PEMParser) Session(org.shredzone.acme4j.Session) BufferedWriter(java.io.BufferedWriter) Optional.ofNullable(java.util.Optional.ofNullable) FileWriter(java.io.FileWriter) IOException(java.io.IOException) Account(org.shredzone.acme4j.Account) File(java.io.File) Executors(java.util.concurrent.Executors) Objects(java.util.Objects) TimeUnit(java.util.concurrent.TimeUnit) Stream(java.util.stream.Stream) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) Writer(java.io.Writer) CliOption(org.apache.meecrowave.runner.cli.CliOption) PEMKeyPair(org.bouncycastle.openssl.PEMKeyPair) AcmeException(org.shredzone.acme4j.exception.AcmeException) FileReader(java.io.FileReader) Cli(org.apache.meecrowave.runner.Cli) Account(org.shredzone.acme4j.Account) KeyPair(java.security.KeyPair) PEMKeyPair(org.bouncycastle.openssl.PEMKeyPair) AcmeException(org.shredzone.acme4j.exception.AcmeException) FileWriter(java.io.FileWriter) IOException(java.io.IOException) BufferedWriter(java.io.BufferedWriter) AccountBuilder(org.shredzone.acme4j.AccountBuilder) CSRBuilder(org.shredzone.acme4j.util.CSRBuilder) JcaPEMWriter(org.bouncycastle.openssl.jcajce.JcaPEMWriter) BufferedWriter(java.io.BufferedWriter) FileWriter(java.io.FileWriter) Writer(java.io.Writer) Session(org.shredzone.acme4j.Session) Certificate(org.shredzone.acme4j.Certificate)

Example 2 with Session

use of org.shredzone.acme4j.Session in project stdlib by petergeneric.

the class LetsEncryptService method getRegistration.

public Registration getRegistration() {
    if (_registration == null) {
        LetsEncryptAccountEntity existing = accountDao.getById(LetsEncryptAccountEntity.MAIN_ACCOUNT_ID);
        final KeyPair keypair;
        try {
            if (existing != null) {
                ByteArrayInputStream bis = new ByteArrayInputStream(existing.getKeypair());
                InputStreamReader r = new InputStreamReader(bis, StandardCharsets.UTF_8);
                keypair = KeyPairUtils.readKeyPair(r);
            } else {
                keypair = KeyPairUtils.createKeyPair(REGISTRATION_KEY_SIZE);
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                OutputStreamWriter w = new OutputStreamWriter(bos, StandardCharsets.UTF_8);
                KeyPairUtils.writeKeyPair(keypair, w);
                existing = new LetsEncryptAccountEntity();
                existing.setId(LetsEncryptAccountEntity.MAIN_ACCOUNT_ID);
                existing.setKeypair(bos.toByteArray());
                // Save the generated keypair
                accountDao.save(existing);
            }
        } catch (IOException e) {
            throw new RuntimeException("Error creating/loading/saving Let's Encrypt Registration Keypair", e);
        }
        Session session = new Session(acmeServerUri, keypair);
        Registration registration;
        {
            try {
                try {
                    final RegistrationBuilder registrationBuilder = new RegistrationBuilder();
                    registration = registrationBuilder.create(session);
                } catch (AcmeConflictException ex) {
                    registration = Registration.bind(session, ex.getLocation());
                }
                // Automatically accept any agreement updates
                registration.modify().setAgreement(registration.getAgreement()).commit();
            } catch (Exception e) {
                throw new RuntimeException("Unexpected error registering with ACME CA", e);
            }
        }
        _registration = registration;
    }
    return _registration;
}
Also used : KeyPair(java.security.KeyPair) InputStreamReader(java.io.InputStreamReader) LetsEncryptAccountEntity(com.peterphi.servicemanager.service.db.entity.LetsEncryptAccountEntity) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) AcmeConflictException(org.shredzone.acme4j.exception.AcmeConflictException) IOException(java.io.IOException) AcmeException(org.shredzone.acme4j.exception.AcmeException) RegistrationBuilder(org.shredzone.acme4j.RegistrationBuilder) ByteArrayInputStream(java.io.ByteArrayInputStream) Registration(org.shredzone.acme4j.Registration) OutputStreamWriter(java.io.OutputStreamWriter) AcmeConflictException(org.shredzone.acme4j.exception.AcmeConflictException) Session(org.shredzone.acme4j.Session)

Example 3 with Session

use of org.shredzone.acme4j.Session in project webpieces by deanhiller.

the class AcmeClientProxy method fetchRemoteInfo.

// TODO: Put the remote request INTO a different pool to not hold up the webserver main
// threadpool so only synchronous requests will hold up synchronous requests
public XFuture<AcmeInfo> fetchRemoteInfo() {
    try {
        Session session = new Session(config.getProviderLocation());
        Metadata metadata = session.getMetadata();
        URI termsOfServiceUri = metadata.getTermsOfService();
        URL website = metadata.getWebsite();
        return XFuture.completedFuture(new AcmeInfo(termsOfServiceUri, website));
    } catch (AcmeException e) {
        throw SneakyThrow.sneak(e);
    }
}
Also used : AcmeException(org.shredzone.acme4j.exception.AcmeException) Metadata(org.shredzone.acme4j.Metadata) URI(java.net.URI) URL(java.net.URL) Session(org.shredzone.acme4j.Session)

Example 4 with Session

use of org.shredzone.acme4j.Session in project webpieces by deanhiller.

the class AcmeClientProxy method openAccount.

// TODO: Put the remote request INTO a different pool to not hold up the webserver main
// threadpool so only synchronous requests will hold up synchronous requests
public XFuture<URL> openAccount(String email, KeyPair accountKeyPair) {
    try {
        log.info("open account");
        Session session = new Session("acme://letsencrypt.org/staging");
        Account account = new AccountBuilder().addContact("mailto:" + email).agreeToTermsOfService().useKeyPair(accountKeyPair).create(session);
        URL location = account.getLocation();
        log.info("account location=" + location);
        return XFuture.completedFuture(location);
    } catch (AcmeException e) {
        throw SneakyThrow.sneak(e);
    }
}
Also used : Account(org.shredzone.acme4j.Account) AcmeException(org.shredzone.acme4j.exception.AcmeException) AccountBuilder(org.shredzone.acme4j.AccountBuilder) URL(java.net.URL) Session(org.shredzone.acme4j.Session)

Example 5 with Session

use of org.shredzone.acme4j.Session in project webpieces by deanhiller.

the class AcmeClientProxy method placeOrder.

// TODO: Put the remote request INTO a different pool to not hold up the webserver main
// threadpool so only synchronous requests will hold up synchronous requests
/**
 * @return The list of challenges with tokens to create webpages for that remote end will call to verify we own the domain
 */
public XFuture<ProxyOrder> placeOrder(URL accountUrl, KeyPair accountKeyPair) {
    try {
        log.info("reestablish account from location=" + accountUrl + " and keypair");
        Session session = new Session("acme://letsencrypt.org/staging");
        Login login = session.login(accountUrl, accountKeyPair);
        Account account = login.getAccount();
        log.info("create an order");
        String domainTemp = "something.com";
        Order order = account.newOrder().domain(domainTemp).create();
        checkAuthStatii(order);
        List<ProxyAuthorization> auths = new ArrayList<>();
        for (Authorization auth : order.getAuthorizations()) auths.add(new ProxyAuthorization(auth));
        return XFuture.completedFuture(new ProxyOrder(order, auths));
    } catch (AcmeException e) {
        throw SneakyThrow.sneak(e);
    }
}
Also used : Order(org.shredzone.acme4j.Order) Authorization(org.shredzone.acme4j.Authorization) Account(org.shredzone.acme4j.Account) AcmeException(org.shredzone.acme4j.exception.AcmeException) ArrayList(java.util.ArrayList) Login(org.shredzone.acme4j.Login) Session(org.shredzone.acme4j.Session)

Aggregations

Session (org.shredzone.acme4j.Session)6 AcmeException (org.shredzone.acme4j.exception.AcmeException)5 Account (org.shredzone.acme4j.Account)3 FileWriter (java.io.FileWriter)2 IOException (java.io.IOException)2 URL (java.net.URL)2 KeyPair (java.security.KeyPair)2 AccountBuilder (org.shredzone.acme4j.AccountBuilder)2 Authorization (org.shredzone.acme4j.Authorization)2 Order (org.shredzone.acme4j.Order)2 CSRBuilder (org.shredzone.acme4j.util.CSRBuilder)2 LetsEncryptAccountEntity (com.peterphi.servicemanager.service.db.entity.LetsEncryptAccountEntity)1 BufferedWriter (java.io.BufferedWriter)1 ByteArrayInputStream (java.io.ByteArrayInputStream)1 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 File (java.io.File)1 FileReader (java.io.FileReader)1 InputStreamReader (java.io.InputStreamReader)1 OutputStreamWriter (java.io.OutputStreamWriter)1 Writer (java.io.Writer)1