Search in sources :

Example 11 with Request

use of org.bouncycastle.asn1.ocsp.Request in project athenz by yahoo.

the class ZTSClient method getAWSTemporaryCredentials.

public AWSTemporaryCredentials getAWSTemporaryCredentials(String domainName, String roleName, boolean ignoreCache) {
    try {
        roleName = URLEncoder.encode(roleName, "UTF-8");
    } catch (UnsupportedEncodingException ex) {
        LOG.error("Unable to encode {} - error {}", roleName, ex.getMessage());
    }
    // first lookup in our cache to see if it can be satisfied
    // only if we're not asked to ignore the cache
    AWSTemporaryCredentials awsCred = null;
    String cacheKey = getRoleTokenCacheKey(domainName, roleName, null);
    if (cacheKey != null && !ignoreCache) {
        awsCred = lookupAwsCredInCache(cacheKey, null, null);
        if (awsCred != null) {
            return awsCred;
        }
        if (enablePrefetch && prefetchAutoEnable) {
            if (prefetchAwsCred(domainName, roleName, null, null)) {
                awsCred = lookupAwsCredInCache(cacheKey, null, null);
            }
            if (awsCred != null) {
                return awsCred;
            }
            LOG.error("GetAWSTemporaryCredentials: cache prefetch and lookup error");
        }
    }
    // if no hit then we need to request a new token from ZTS
    updateServicePrincipal();
    try {
        awsCred = ztsClient.getAWSTemporaryCredentials(domainName, roleName);
    } catch (ResourceException ex) {
        throw new ZTSClientException(ex.getCode(), ex.getData());
    } catch (Exception ex) {
        throw new ZTSClientException(ZTSClientException.BAD_REQUEST, ex.getMessage());
    }
    if (awsCred != null) {
        if (cacheKey == null) {
            cacheKey = getRoleTokenCacheKey(domainName, roleName, null);
        }
        if (cacheKey != null) {
            AWS_CREDS_CACHE.put(cacheKey, awsCred);
        }
    }
    return awsCred;
}
Also used : UnsupportedEncodingException(java.io.UnsupportedEncodingException) DERIA5String(org.bouncycastle.asn1.DERIA5String) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) CertificateParsingException(java.security.cert.CertificateParsingException) CryptoException(com.yahoo.athenz.auth.util.CryptoException) IOException(java.io.IOException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) SSLPeerUnverifiedException(javax.net.ssl.SSLPeerUnverifiedException)

Example 12 with Request

use of org.bouncycastle.asn1.ocsp.Request in project athenz by yahoo.

the class InstanceClientRegister method main.

public static void main(String[] args) throws MalformedURLException, IOException {
    // parse our command line to retrieve required input
    CommandLine cmd = parseCommandLine(args);
    String domainName = cmd.getOptionValue("domain").toLowerCase();
    String serviceName = cmd.getOptionValue("service").toLowerCase();
    String provider = cmd.getOptionValue("provider").toLowerCase();
    String instance = cmd.getOptionValue("instance");
    String dnsSuffix = cmd.getOptionValue("dnssuffix");
    String providerKeyPath = cmd.getOptionValue("providerkey");
    String providerKeyId = cmd.getOptionValue("providerkeyid");
    String instanceKeyPath = cmd.getOptionValue("instancekey");
    String ztsUrl = cmd.getOptionValue("ztsurl");
    // get our configured private key
    PrivateKey providerKey = Crypto.loadPrivateKey(new File(providerKeyPath));
    // first we are going to generate our attestation data
    // which we are going to use jwt. ZTS Server will send
    // this object to the specified provider for validation
    String compactJws = Jwts.builder().setSubject(domainName + "." + serviceName).setIssuer(provider).setAudience("zts").setId(instance).setExpiration(new Date(System.currentTimeMillis() + TimeUnit.MILLISECONDS.convert(5, TimeUnit.MINUTES))).setHeaderParam("keyId", providerKeyId).signWith(SignatureAlgorithm.RS256, providerKey).compact();
    System.out.println("JWS: \n" + compactJws + "\n");
    // now we need to generate our CSR so we can get
    // a TLS certificate for our instance
    PrivateKey instanceKey = Crypto.loadPrivateKey(new File(instanceKeyPath));
    String csr = generateCSR(domainName, serviceName, instance, dnsSuffix, instanceKey);
    if (csr == null) {
        System.err.println("Unable to generate CSR for instance");
        System.exit(1);
    }
    System.out.println("CSR: \n" + csr + "\n");
    // now let's generate our instance register object that will be sent
    // to the ZTS Server
    InstanceRegisterInformation info = new InstanceRegisterInformation().setAttestationData(compactJws).setDomain(domainName).setService(serviceName).setProvider(provider).setToken(true).setCsr(csr);
    // now contact zts server to request identity for instance
    InstanceIdentity identity = null;
    Map<String, List<String>> responseHeaders = new HashMap<>();
    try (ZTSClient ztsClient = new ZTSClient(ztsUrl)) {
        identity = ztsClient.postInstanceRegisterInformation(info, responseHeaders);
    } catch (ZTSClientException ex) {
        System.out.println("Unable to register instance: " + ex.getMessage());
        System.exit(2);
    }
    System.out.println("Identity TLS Certificate: \n" + identity.getX509Certificate());
    Map<String, String> attrs = identity.getAttributes();
    if (attrs != null) {
        System.out.println("Provider Attributes:");
        for (String key : attrs.keySet()) {
            System.out.println("\t" + key + ": " + attrs.get(key));
        }
    }
}
Also used : PrivateKey(java.security.PrivateKey) HashMap(java.util.HashMap) InstanceRegisterInformation(com.yahoo.athenz.zts.InstanceRegisterInformation) ZTSClient(com.yahoo.athenz.zts.ZTSClient) DERIA5String(org.bouncycastle.asn1.DERIA5String) InstanceIdentity(com.yahoo.athenz.zts.InstanceIdentity) Date(java.util.Date) CommandLine(org.apache.commons.cli.CommandLine) List(java.util.List) ZTSClientException(com.yahoo.athenz.zts.ZTSClientException) File(java.io.File)

Example 13 with Request

use of org.bouncycastle.asn1.ocsp.Request in project pdfbox by apache.

the class TSAClient method getTimeStampToken.

/**
 * @param messageImprint imprint of message contents
 * @return the encoded time stamp token
 * @throws IOException if there was an error with the connection or data from the TSA server,
 *                     or if the time stamp response could not be validated
 */
public byte[] getTimeStampToken(byte[] messageImprint) throws IOException {
    digest.reset();
    byte[] hash = digest.digest(messageImprint);
    // 32-bit cryptographic nonce
    SecureRandom random = new SecureRandom();
    int nonce = random.nextInt();
    // generate TSA request
    TimeStampRequestGenerator tsaGenerator = new TimeStampRequestGenerator();
    tsaGenerator.setCertReq(true);
    ASN1ObjectIdentifier oid = getHashObjectIdentifier(digest.getAlgorithm());
    TimeStampRequest request = tsaGenerator.generate(oid, hash, BigInteger.valueOf(nonce));
    // get TSA response
    byte[] tsaResponse = getTSAResponse(request.getEncoded());
    TimeStampResponse response;
    try {
        response = new TimeStampResponse(tsaResponse);
        response.validate(request);
    } catch (TSPException e) {
        throw new IOException(e);
    }
    TimeStampToken token = response.getTimeStampToken();
    if (token == null) {
        throw new IOException("Response does not have a time stamp token");
    }
    return token.getEncoded();
}
Also used : TimeStampResponse(org.bouncycastle.tsp.TimeStampResponse) SecureRandom(java.security.SecureRandom) TimeStampRequestGenerator(org.bouncycastle.tsp.TimeStampRequestGenerator) TSPException(org.bouncycastle.tsp.TSPException) IOException(java.io.IOException) TimeStampToken(org.bouncycastle.tsp.TimeStampToken) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier) TimeStampRequest(org.bouncycastle.tsp.TimeStampRequest)

Example 14 with Request

use of org.bouncycastle.asn1.ocsp.Request in project pdfbox by apache.

the class OcspHelper method verifyRespStatus.

/**
 * Helper method to verify response status.
 *
 * @param resp OCSP response
 * @throws OCSPException if the response status is not ok
 */
public void verifyRespStatus(OCSPResp resp) throws OCSPException {
    String statusInfo = "";
    if (resp != null) {
        int status = resp.getStatus();
        switch(status) {
            case OCSPResponseStatus.INTERNAL_ERROR:
                statusInfo = "INTERNAL_ERROR";
                System.err.println("An internal error occurred in the OCSP Server!");
                break;
            case OCSPResponseStatus.MALFORMED_REQUEST:
                statusInfo = "MALFORMED_REQUEST";
                System.err.println("Your request did not fit the RFC 2560 syntax!");
                break;
            case OCSPResponseStatus.SIG_REQUIRED:
                statusInfo = "SIG_REQUIRED";
                System.err.println("Your request was not signed!");
                break;
            case OCSPResponseStatus.TRY_LATER:
                statusInfo = "TRY_LATER";
                System.err.println("The server was too busy to answer you!");
                break;
            case OCSPResponseStatus.UNAUTHORIZED:
                statusInfo = "UNAUTHORIZED";
                System.err.println("The server could not authenticate you!");
                break;
            case OCSPResponseStatus.SUCCESSFUL:
                break;
            default:
                statusInfo = "UNKNOWN";
                System.err.println("Unknown OCSPResponse status code! " + status);
        }
    }
    if (resp == null || resp.getStatus() != OCSPResponseStatus.SUCCESSFUL) {
        throw new OCSPException(statusInfo + "OCSP response unsuccessful! ");
    }
}
Also used : OCSPException(org.bouncycastle.cert.ocsp.OCSPException) DEROctetString(org.bouncycastle.asn1.DEROctetString)

Example 15 with Request

use of org.bouncycastle.asn1.ocsp.Request in project keystore-explorer by kaikramer.

the class Pkcs10Util method generateCsr.

/**
 * Create a PKCS #10 certificate signing request (CSR) using the supplied
 * certificate, private key and signature algorithm.
 *
 * @param cert
 *            The certificate
 * @param privateKey
 *            The private key
 * @param signatureType
 *            Signature
 * @param challenge
 *            Challenge, optional, pass null if not required
 * @param unstructuredName
 *            An optional company name, pass null if not required
 * @param useExtensions
 *            Use extensions from cert for extensionRequest attribute?
 * @throws CryptoException
 *             If there was a problem generating the CSR
 * @return The CSR
 */
public static PKCS10CertificationRequest generateCsr(X509Certificate cert, PrivateKey privateKey, SignatureType signatureType, String challenge, String unstructuredName, boolean useExtensions, Provider provider) throws CryptoException {
    try {
        JcaPKCS10CertificationRequestBuilder csrBuilder = new JcaPKCS10CertificationRequestBuilder(cert.getSubjectX500Principal(), cert.getPublicKey());
        // add challenge attribute
        if (challenge != null) {
            // PKCS#9 2.0: SHOULD use UTF8String encoding
            csrBuilder.addAttribute(pkcs_9_at_challengePassword, new DERUTF8String(challenge));
        }
        if (unstructuredName != null) {
            csrBuilder.addAttribute(pkcs_9_at_unstructuredName, new DERUTF8String(unstructuredName));
        }
        if (useExtensions) {
            // add extensionRequest attribute with all extensions from the certificate
            Certificate certificate = Certificate.getInstance(cert.getEncoded());
            Extensions extensions = certificate.getTBSCertificate().getExtensions();
            if (extensions != null) {
                csrBuilder.addAttribute(pkcs_9_at_extensionRequest, extensions.toASN1Primitive());
            }
        }
        // fall back to bouncy castle provider if given provider does not support the requested algorithm
        if (provider != null && provider.getService("Signature", signatureType.jce()) == null) {
            provider = new BouncyCastleProvider();
        }
        ContentSigner contentSigner = null;
        if (provider == null) {
            contentSigner = new JcaContentSignerBuilder(signatureType.jce()).build(privateKey);
        } else {
            contentSigner = new JcaContentSignerBuilder(signatureType.jce()).setProvider(provider).build(privateKey);
        }
        PKCS10CertificationRequest csr = csrBuilder.build(contentSigner);
        if (!verifyCsr(csr)) {
            throw new CryptoException(res.getString("NoVerifyGenPkcs10Csr.exception.message"));
        }
        return csr;
    } catch (CertificateEncodingException e) {
        throw new CryptoException(res.getString("NoGeneratePkcs10Csr.exception.message"), e);
    } catch (OperatorCreationException e) {
        throw new CryptoException(res.getString("NoGeneratePkcs10Csr.exception.message"), e);
    }
}
Also used : PKCS10CertificationRequest(org.bouncycastle.pkcs.PKCS10CertificationRequest) JcaPKCS10CertificationRequest(org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequest) DERUTF8String(org.bouncycastle.asn1.DERUTF8String) JcaPKCS10CertificationRequestBuilder(org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) ContentSigner(org.bouncycastle.operator.ContentSigner) CertificateEncodingException(java.security.cert.CertificateEncodingException) Extensions(org.bouncycastle.asn1.x509.Extensions) CryptoException(org.kse.crypto.CryptoException) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) X509Certificate(java.security.cert.X509Certificate) Certificate(org.bouncycastle.asn1.x509.Certificate) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider)

Aggregations

IOException (java.io.IOException)47 ASN1OctetString (org.bouncycastle.asn1.ASN1OctetString)30 Date (java.util.Date)27 DEROctetString (org.bouncycastle.asn1.DEROctetString)26 BigInteger (java.math.BigInteger)23 X509Certificate (java.security.cert.X509Certificate)22 PKIMessage (org.bouncycastle.asn1.cmp.PKIMessage)22 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)20 CertificateException (java.security.cert.CertificateException)18 ArrayList (java.util.ArrayList)17 DERUTF8String (org.bouncycastle.asn1.DERUTF8String)17 X500Name (org.bouncycastle.asn1.x500.X500Name)16 Extension (org.bouncycastle.asn1.x509.Extension)16 Extensions (org.bouncycastle.asn1.x509.Extensions)16 ASN1Integer (org.bouncycastle.asn1.ASN1Integer)15 DERIA5String (org.bouncycastle.asn1.DERIA5String)15 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)14 PKIBody (org.bouncycastle.asn1.cmp.PKIBody)13 ASN1Sequence (org.bouncycastle.asn1.ASN1Sequence)12 GeneralName (org.bouncycastle.asn1.x509.GeneralName)11