Example usage for java.security.cert X509Certificate getSubjectDN

List of usage examples for java.security.cert X509Certificate getSubjectDN

Introduction

In this page you can find the example usage for java.security.cert X509Certificate getSubjectDN.

Prototype

public abstract Principal getSubjectDN();

Source Link

Document

Denigrated, replaced by #getSubjectX500Principal() .

Usage

From source file:org.ejbca.core.protocol.cmp.CrmfRAPbeMultipleKeyIdRequestTest.java

@Test
public void test03CrmfTcpOkUserKeyId1() throws Exception {

    byte[] nonce = CmpMessageHelper.createSenderNonce();
    byte[] transid = CmpMessageHelper.createSenderNonce();

    PKIMessage one = genCertReq(this.issuerDN1, userDN1, this.keys, this.cacert1, nonce, transid, true, null,
            null, null, null, null, null);
    PKIMessage req = protectPKIMessage(one, false, PBEPASSWORD, "KeyId1", 567);

    CertReqMessages ir = (CertReqMessages) req.getBody().getContent();
    int reqId = ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue();
    assertNotNull(req);/*from  w  ww. java 2  s . c o m*/
    ByteArrayOutputStream bao = new ByteArrayOutputStream();
    DEROutputStream out = new DEROutputStream(bao);
    out.writeObject(req);
    byte[] ba = bao.toByteArray();
    // Send request and receive response
    byte[] resp = sendCmpTcp(ba, 5);
    checkCmpResponseGeneral(resp, this.issuerDN1, userDN1, this.cacert1, nonce, transid, false, PBEPASSWORD,
            PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
    X509Certificate cert = checkCmpCertRepMessage(userDN1, this.cacert1, resp, reqId);
    String altNames = CertTools.getSubjectAlternativeName(cert);
    assertTrue(altNames.indexOf("upn=fooupn@bar.com") != -1);
    assertTrue(altNames.indexOf("rfc822name=fooemail@bar.com") != -1);

    // Check key usage that it is digitalSignature for KeyId1 and
    // nonRepudiation for KeyId2
    boolean[] ku = cert.getKeyUsage();
    assertTrue(ku[0]);
    assertFalse(ku[1]);
    assertFalse(ku[2]);
    assertFalse(ku[3]);
    assertFalse(ku[4]);
    assertFalse(ku[5]);
    assertFalse(ku[6]);
    assertFalse(ku[7]);
    assertFalse(ku[8]);
    // Check DN that must be SE for KeyId1
    assertEquals("SE", CertTools.getPartFromDN(cert.getSubjectDN().getName(), "C"));

    // Send a confirm message to the CA
    String hash = "foo123";
    PKIMessage confirm = genCertConfirm(userDN1, this.cacert1, nonce, transid, hash, reqId);
    assertNotNull(confirm);
    PKIMessage req1 = protectPKIMessage(confirm, false, PBEPASSWORD, 567);
    bao = new ByteArrayOutputStream();
    out = new DEROutputStream(bao);
    out.writeObject(req1);
    ba = bao.toByteArray();
    // Send request and receive response
    resp = sendCmpTcp(ba, 5);
    checkCmpResponseGeneral(resp, this.issuerDN1, userDN1, this.cacert1, nonce, transid, false, PBEPASSWORD,
            PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
    checkCmpPKIConfirmMessage(userDN1, this.cacert1, resp);
}

From source file:org.apache.rampart.PolicyBasedResultsValidator.java

/**
 * Evaluate whether a given certificate should be trusted. Hook to allow subclasses to implement
 * custom validation methods however they see fit.
 * <p/>/*from ww  w.j a  v  a  2  s. c  o  m*/
 * Policy used in this implementation: 1. Search the keystore for the transmitted certificate 2.
 * Search the keystore for a connection to the transmitted certificate (that is, search for
 * certificate(s) of the issuer of the transmitted certificate 3. Verify the trust path for
 * those certificates found because the search for the issuer might be fooled by a phony DN
 * (String!)
 *
 * @param cert the certificate that should be validated against the keystore
 * @return true if the certificate is trusted, false if not (AxisFault is thrown for exceptions
 *         during CertPathValidation)
 * @throws WSSecurityException
 */
protected boolean verifyTrust(X509Certificate cert, RampartMessageData rmd) throws RampartException {

    // If no certificate was transmitted, do not trust the signature
    if (cert == null) {
        return false;
    }

    String[] aliases = null;
    String alias = null;
    X509Certificate[] certs;

    String subjectString = cert.getSubjectDN().getName();
    String issuerString = cert.getIssuerDN().getName();
    BigInteger issuerSerial = cert.getSerialNumber();

    boolean doDebug = log.isDebugEnabled();

    if (doDebug) {
        log.debug("WSHandler: Transmitted certificate has subject " + subjectString);
        log.debug("WSHandler: Transmitted certificate has issuer " + issuerString + " (serial " + issuerSerial
                + ")");
    }

    // FIRST step
    // Search the keystore for the transmitted certificate

    // Search the keystore for the alias of the transmitted certificate
    try {
        alias = RampartUtil
                .getSignatureCrypto(rmd.getPolicyData().getRampartConfig(), rmd.getCustomClassLoader())
                .getAliasForX509Cert(issuerString, issuerSerial);
    } catch (WSSecurityException ex) {
        throw new RampartException("cannotFindAliasForCert", new String[] { subjectString }, ex);
    }

    if (alias != null) {
        // Retrieve the certificate for the alias from the keystore
        try {
            certs = RampartUtil
                    .getSignatureCrypto(rmd.getPolicyData().getRampartConfig(), rmd.getCustomClassLoader())
                    .getCertificates(alias);
        } catch (WSSecurityException ex) {
            throw new RampartException("noCertForAlias", new String[] { alias }, ex);
        }

        // If certificates have been found, the certificates must be compared
        // to ensure against phony DNs (compare encoded form including signature)
        if (certs != null && certs.length > 0 && cert.equals(certs[0])) {
            if (doDebug) {
                log.debug("Direct trust for certificate with " + subjectString);
            }
            // Set the alias of the cert used for the msg. sig. as a msg. cxt. property
            rmd.getMsgContext().setProperty(RampartMessageData.SIGNATURE_CERT_ALIAS, alias);
            return true;
        }
    } else {
        if (doDebug) {
            log.debug("No alias found for subject from issuer with " + issuerString + " (serial " + issuerSerial
                    + ")");
        }
    }

    // SECOND step
    // Search for the issuer of the transmitted certificate in the keystore

    // Search the keystore for the alias of the transmitted certificates issuer
    try {
        aliases = RampartUtil
                .getSignatureCrypto(rmd.getPolicyData().getRampartConfig(), rmd.getCustomClassLoader())
                .getAliasesForDN(issuerString);
    } catch (WSSecurityException ex) {
        throw new RampartException("cannotFindAliasForCert", new String[] { issuerString }, ex);
    }

    // If the alias has not been found, the issuer is not in the keystore
    // As a direct result, do not trust the transmitted certificate
    if (aliases == null || aliases.length < 1) {
        if (doDebug) {
            log.debug("No aliases found in keystore for issuer " + issuerString + " of certificate for "
                    + subjectString);
        }
        return false;
    }

    // THIRD step
    // Check the certificate trust path for every alias of the issuer found in the keystore
    for (int i = 0; i < aliases.length; i++) {
        alias = aliases[i];

        if (doDebug) {
            log.debug("Preparing to validate certificate path with alias " + alias + " for issuer "
                    + issuerString);
        }

        // Retrieve the certificate(s) for the alias from the keystore
        try {
            certs = RampartUtil
                    .getSignatureCrypto(rmd.getPolicyData().getRampartConfig(), rmd.getCustomClassLoader())
                    .getCertificates(alias);
        } catch (WSSecurityException ex) {
            throw new RampartException("noCertForAlias", new String[] { alias }, ex);
        }

        // If no certificates have been found, there has to be an error:
        // The keystore can find an alias but no certificate(s)
        if (certs == null || certs.length < 1) {
            throw new RampartException("noCertForAlias", new String[] { alias });
        }

        // Form a certificate chain from the transmitted certificate
        // and the certificate(s) of the issuer from the keystore
        // First, create new array
        X509Certificate[] x509certs = new X509Certificate[certs.length + 1];
        // Then add the first certificate ...
        x509certs[0] = cert;
        // ... and the other certificates
        for (int j = 0; j < certs.length; j++) {
            cert = certs[j];
            x509certs[j + 1] = cert;
        }
        certs = x509certs;

        // Use the validation method from the crypto to check whether the subjects certificate
        // was really signed by the issuer stated in the certificate
        try {
            if (RampartUtil
                    .getSignatureCrypto(rmd.getPolicyData().getRampartConfig(), rmd.getCustomClassLoader())
                    .validateCertPath(certs)) {
                if (doDebug) {
                    log.debug("WSHandler: Certificate path has been verified for certificate with subject "
                            + subjectString);
                }
                return true;
            }
        } catch (WSSecurityException ex) {
            throw new RampartException("certPathVerificationFailed", new String[] { subjectString }, ex);
        }
    }

    if (doDebug) {
        log.debug("WSHandler: Certificate path could not be verified for certificate with subject "
                + subjectString);
    }
    return false;
}

From source file:org.ejbca.core.protocol.cmp.CrmfRAPbeMultipleKeyIdRequestTest.java

@Test
public void test04CrmfTcpOkUserKeyId2() throws Exception {

    byte[] nonce = CmpMessageHelper.createSenderNonce();
    byte[] transid = CmpMessageHelper.createSenderNonce();

    PKIMessage one = genCertReq(this.issuerDN2, userDN2, this.keys, this.cacert2, nonce, transid, true, null,
            null, null, null, null, null);
    PKIMessage req = protectPKIMessage(one, false, PBEPASSWORD, "KeyId2", 567);

    CertReqMessages ir = (CertReqMessages) req.getBody().getContent();
    int reqId = ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue();
    assertNotNull(req);/*  w  w w  .j  av a 2  s.com*/
    ByteArrayOutputStream bao = new ByteArrayOutputStream();
    DEROutputStream out = new DEROutputStream(bao);
    out.writeObject(req);
    byte[] ba = bao.toByteArray();
    // Send request and receive response
    byte[] resp = sendCmpTcp(ba, 5);
    checkCmpResponseGeneral(resp, this.issuerDN2, userDN2, this.cacert2, nonce, transid, false, PBEPASSWORD,
            PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
    X509Certificate cert = checkCmpCertRepMessage(userDN2, this.cacert2, resp, reqId);
    String altNames = CertTools.getSubjectAlternativeName(cert);
    assertTrue(altNames.indexOf("upn=fooupn@bar.com") != -1);
    assertTrue(altNames.indexOf("rfc822name=fooemail@bar.com") != -1);

    // Check key usage that it is digitalSignature for KeyId1 and
    // nonRepudiation for KeyId2
    boolean[] ku = cert.getKeyUsage();
    assertFalse(ku[0]);
    assertTrue(ku[1]);
    assertFalse(ku[2]);
    assertFalse(ku[3]);
    assertFalse(ku[4]);
    assertFalse(ku[5]);
    assertFalse(ku[6]);
    assertFalse(ku[7]);
    assertFalse(ku[8]);
    // Check DN that must be SE for KeyId1 and NO for KeyId2
    assertEquals("NO", CertTools.getPartFromDN(cert.getSubjectDN().getName(), "C"));

    // Send a confirm message to the CA
    String hash = "foo123";
    PKIMessage confirm = genCertConfirm(userDN2, this.cacert2, nonce, transid, hash, reqId);
    assertNotNull(confirm);
    PKIMessage req1 = protectPKIMessage(confirm, false, PBEPASSWORD, 567);
    bao = new ByteArrayOutputStream();
    out = new DEROutputStream(bao);
    out.writeObject(req1);
    ba = bao.toByteArray();
    // Send request and receive response
    resp = sendCmpTcp(ba, 5);
    checkCmpResponseGeneral(resp, this.issuerDN2, userDN2, this.cacert2, nonce, transid, false, PBEPASSWORD,
            PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
    checkCmpPKIConfirmMessage(userDN2, this.cacert2, resp);
}

From source file:org.ejbca.core.protocol.cmp.CrmfRAPbeMultipleKeyIdRequestTest.java

@Test
public void test02CrmfHttpOkUserKeyId1() throws Exception {

    byte[] nonce = CmpMessageHelper.createSenderNonce();
    byte[] transid = CmpMessageHelper.createSenderNonce();

    PKIMessage one = genCertReq(this.issuerDN1, userDN1, this.keys, this.cacert1, nonce, transid, true, null,
            null, null, null, null, null);
    PKIMessage req = protectPKIMessage(one, false, PBEPASSWORD, "KeyId1", 567);

    CertReqMessages ir = (CertReqMessages) req.getBody().getContent();
    int reqId = ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue();
    assertNotNull(req);/*from   w  ww.j  a v  a 2 s  . c  om*/
    ByteArrayOutputStream bao = new ByteArrayOutputStream();
    DEROutputStream out = new DEROutputStream(bao);
    out.writeObject(req);
    byte[] ba = bao.toByteArray();
    // Send request and receive response
    byte[] resp = sendCmpHttp(ba, 200, configAlias);
    checkCmpResponseGeneral(resp, this.issuerDN1, userDN1, this.cacert1, nonce, transid, false, PBEPASSWORD,
            PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
    X509Certificate cert = checkCmpCertRepMessage(userDN1, this.cacert1, resp, reqId);
    String altNames = CertTools.getSubjectAlternativeName(cert);
    assertTrue(altNames.indexOf("upn=fooupn@bar.com") != -1);
    assertTrue(altNames.indexOf("rfc822name=fooemail@bar.com") != -1);

    // Check key usage that it is digitalSignature for KeyId1 and
    // nonRepudiation for KeyId2
    boolean[] ku = cert.getKeyUsage();
    assertTrue(ku[0]);
    assertFalse(ku[1]);
    assertFalse(ku[2]);
    assertFalse(ku[3]);
    assertFalse(ku[4]);
    assertFalse(ku[5]);
    assertFalse(ku[6]);
    assertFalse(ku[7]);
    assertFalse(ku[8]);
    // Check DN that must be SE for KeyId1
    assertEquals("SE", CertTools.getPartFromDN(cert.getSubjectDN().getName(), "C"));

    // Send a confirm message to the CA
    String hash = "foo123";
    PKIMessage confirm = genCertConfirm(userDN1, this.cacert1, nonce, transid, hash, reqId);
    assertNotNull(confirm);
    PKIMessage req1 = protectPKIMessage(confirm, false, PBEPASSWORD, 567);
    bao = new ByteArrayOutputStream();
    out = new DEROutputStream(bao);
    out.writeObject(req1);
    ba = bao.toByteArray();
    // Send request and receive response
    resp = sendCmpHttp(ba, 200, configAlias);
    checkCmpResponseGeneral(resp, this.issuerDN1, userDN1, this.cacert1, nonce, transid, false, PBEPASSWORD,
            PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
    checkCmpPKIConfirmMessage(userDN1, this.cacert1, resp);

    // Now revoke the bastard!
    PKIMessage rev = genRevReq(this.issuerDN1, userDN1, cert.getSerialNumber(), this.cacert1, nonce, transid,
            true, null, null);
    PKIMessage revReq = protectPKIMessage(rev, false, PBEPASSWORD, 567);
    assertNotNull(revReq);
    bao = new ByteArrayOutputStream();
    out = new DEROutputStream(bao);
    out.writeObject(revReq);
    ba = bao.toByteArray();
    // Send request and receive response
    resp = sendCmpHttp(ba, 200, configAlias);
    checkCmpResponseGeneral(resp, this.issuerDN1, userDN1, this.cacert1, nonce, transid, false, PBEPASSWORD,
            PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
    checkCmpRevokeConfirmMessage(this.issuerDN1, userDN1, cert.getSerialNumber(), this.cacert1, resp, true);
    int reason = checkRevokeStatus(this.issuerDN1, cert.getSerialNumber());
    assertEquals(reason, RevokedCertInfo.REVOCATION_REASON_CESSATIONOFOPERATION);

    // Create a revocation request for a non existing cert, chould fail!
    rev = genRevReq(this.issuerDN1, userDN1, new BigInteger("1"), this.cacert1, nonce, transid, true, null,
            null);
    revReq = protectPKIMessage(rev, false, PBEPASSWORD, 567);
    assertNotNull(revReq);
    bao = new ByteArrayOutputStream();
    out = new DEROutputStream(bao);
    out.writeObject(revReq);
    ba = bao.toByteArray();
    // Send request and receive response
    resp = sendCmpHttp(ba, 200, configAlias);
    checkCmpResponseGeneral(resp, this.issuerDN1, userDN1, this.cacert1, nonce, transid, false, PBEPASSWORD,
            PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
    checkCmpRevokeConfirmMessage(this.issuerDN1, userDN1, cert.getSerialNumber(), this.cacert1, resp, false);

}

From source file:org.dogtagpki.server.rest.UserService.java

public UserCertData createUserCertData(String userID, X509Certificate cert) throws Exception {

    UserCertData userCertData = new UserCertData();

    userCertData.setVersion(cert.getVersion());
    userCertData.setSerialNumber(new CertId(cert.getSerialNumber()));
    userCertData.setIssuerDN(cert.getIssuerDN().toString());
    userCertData.setSubjectDN(cert.getSubjectDN().toString());

    userID = URLEncoder.encode(userID, "UTF-8");
    String certID = URLEncoder.encode(userCertData.getID(), "UTF-8");
    URI uri = uriInfo.getBaseUriBuilder().path(UserResource.class).path("{userID}/certs/{certID}").build(userID,
            certID);//from w w  w  .  j a  v a  2  s.c om
    userCertData.setLink(new Link("self", uri));

    return userCertData;
}

From source file:org.ejbca.core.protocol.cmp.CrmfRAPbeMultipleKeyIdRequestTest.java

@Test
public void test05CrmfHttpOkUserKeyId2() throws Exception {

    byte[] nonce = CmpMessageHelper.createSenderNonce();
    byte[] transid = CmpMessageHelper.createSenderNonce();

    PKIMessage one = genCertReq(this.issuerDN2, userDN2, this.keys, this.cacert2, nonce, transid, true, null,
            null, null, null, null, null);
    PKIMessage req = protectPKIMessage(one, false, PBEPASSWORD, "KeyId2", 567);

    CertReqMessages ir = (CertReqMessages) req.getBody().getContent();
    int reqId = ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue();
    assertNotNull(req);// ww  w  .  j  av  a 2s  .  c  o  m
    ByteArrayOutputStream bao = new ByteArrayOutputStream();
    DEROutputStream out = new DEROutputStream(bao);
    out.writeObject(req);
    byte[] ba = bao.toByteArray();
    // Send request and receive response
    byte[] resp = sendCmpHttp(ba, 200, configAlias);
    checkCmpResponseGeneral(resp, this.issuerDN2, userDN2, this.cacert2, nonce, transid, false, PBEPASSWORD,
            PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
    X509Certificate cert = checkCmpCertRepMessage(userDN2, this.cacert2, resp, reqId);
    String altNames = CertTools.getSubjectAlternativeName(cert);
    assertTrue(altNames.indexOf("upn=fooupn@bar.com") != -1);
    assertTrue(altNames.indexOf("rfc822name=fooemail@bar.com") != -1);

    // Check key usage that it is digitalSignature for KeyId1 and
    // nonRepudiation for KeyId2
    boolean[] ku = cert.getKeyUsage();
    assertFalse(ku[0]);
    assertTrue(ku[1]);
    assertFalse(ku[2]);
    assertFalse(ku[3]);
    assertFalse(ku[4]);
    assertFalse(ku[5]);
    assertFalse(ku[6]);
    assertFalse(ku[7]);
    assertFalse(ku[8]);
    // Check DN that must be SE for KeyId1 and NO for KeyId2
    assertEquals("NO", CertTools.getPartFromDN(cert.getSubjectDN().getName(), "C"));

    // Send a confirm message to the CA
    String hash = "foo123";
    PKIMessage confirm = genCertConfirm(userDN2, this.cacert2, nonce, transid, hash, reqId);
    assertNotNull(confirm);
    PKIMessage req1 = protectPKIMessage(confirm, false, PBEPASSWORD, 567);
    bao = new ByteArrayOutputStream();
    out = new DEROutputStream(bao);
    out.writeObject(req1);
    ba = bao.toByteArray();
    // Send request and receive response
    resp = sendCmpHttp(ba, 200, configAlias);
    checkCmpResponseGeneral(resp, this.issuerDN2, userDN2, this.cacert2, nonce, transid, false, PBEPASSWORD,
            PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
    checkCmpPKIConfirmMessage(userDN2, this.cacert2, resp);

    // Now revoke the bastard!
    PKIMessage rev = genRevReq(this.issuerDN2, userDN2, cert.getSerialNumber(), this.cacert2, nonce, transid,
            true, null, null);
    PKIMessage revReq = protectPKIMessage(rev, false, PBEPASSWORD, 567);
    assertNotNull(revReq);
    bao = new ByteArrayOutputStream();
    out = new DEROutputStream(bao);
    out.writeObject(revReq);
    ba = bao.toByteArray();
    // Send request and receive response
    resp = sendCmpHttp(ba, 200, configAlias);
    checkCmpResponseGeneral(resp, this.issuerDN2, userDN2, this.cacert2, nonce, transid, false, PBEPASSWORD,
            PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
    checkCmpRevokeConfirmMessage(this.issuerDN2, userDN2, cert.getSerialNumber(), this.cacert2, resp, true);
    int reason = checkRevokeStatus(this.issuerDN2, cert.getSerialNumber());
    assertEquals(reason, RevokedCertInfo.REVOCATION_REASON_CESSATIONOFOPERATION);
}

From source file:org.signserver.admin.gui.ViewCertificateFrame.java

private void viewCertificate(final X509Certificate certificate) {
    this.certificate = certificate;
    if (certificate == null) {
        fields = null;// w  w w .  j  a  v a  2 s .  c  om

    } else {
        fields = new ArrayList<Field>();

        fields.add(new Field("Version", String.valueOf(certificate.getVersion())));
        fields.add(new Field("Serial Number", certificate.getSerialNumber().toString(16)));
        fields.add(new Field("Certificate Signature Algorithm", String.valueOf(certificate.getSigAlgName())));
        fields.add(new Field("Issuer", String.valueOf(certificate.getIssuerDN())));
        fields.add(new Field("Validity Not Before", String.valueOf(certificate.getNotBefore())));
        fields.add(new Field("Validity Not After", String.valueOf(certificate.getNotAfter())));
        fields.add(new Field("Subject", String.valueOf(certificate.getSubjectDN())));
        fields.add(new Field("Subject Public Key Algorithm",
                String.valueOf(certificate.getPublicKey().getAlgorithm())));
        fields.add(new Field("Subject's Public Key",
                new String(Hex.encode(certificate.getPublicKey().getEncoded()))));
        if (certificate.getCriticalExtensionOIDs() != null) {
            for (String extensionOid : certificate.getCriticalExtensionOIDs()) {
                fields.add(new Field("Critical extension: " + extensionOid, "<Not supported yet>"));
            }
        }
        if (certificate.getNonCriticalExtensionOIDs() != null) {
            for (String extensionOid : certificate.getNonCriticalExtensionOIDs()) {
                fields.add(new Field("Non critical extension: " + extensionOid, "<Not supported yet>"));
            }
        }
        fields.add(new Field("Certificate Signature Algorithm", String.valueOf(certificate.getSigAlgName())));
        fields.add(
                new Field("Certificate Signature Value", new String(Hex.encode(certificate.getSignature()))));

        fieldsList.setModel(new AbstractListModel() {

            @Override
            public int getSize() {
                return fields.size();
            }

            @Override
            public Object getElementAt(int index) {
                return fields.get(index);
            }
        });
    }
}

From source file:net.solarnetwork.node.setup.impl.DefaultKeystoreService.java

@Override
public boolean isNodeCertificateValid(String issuerDN) throws CertificateException {
    KeyStore keyStore = loadKeyStore();
    X509Certificate x509 = null;/*from w  ww. jav a2  s  . c  om*/
    try {
        if (keyStore == null || !keyStore.containsAlias(nodeAlias)) {
            return false;
        }
        Certificate cert = keyStore.getCertificate(nodeAlias);
        if (!(cert instanceof X509Certificate)) {
            return false;
        }
        x509 = (X509Certificate) cert;
        x509.checkValidity();
        X500Principal issuer = new X500Principal(issuerDN);
        if (!x509.getIssuerX500Principal().equals(issuer)) {
            log.debug("Certificate issuer {} not same as expected {}", x509.getIssuerX500Principal().getName(),
                    issuer.getName());
            return false;
        }
        return true;
    } catch (KeyStoreException e) {
        throw new CertificateException("Error checking for node certificate", e);
    } catch (CertificateExpiredException e) {
        log.debug("Certificate {} has expired", x509.getSubjectDN().getName());
    } catch (CertificateNotYetValidException e) {
        log.debug("Certificate {} not valid yet", x509.getSubjectDN().getName());
    }
    return false;
}

From source file:org.apache.nifi.processors.standard.PostHTTP.java

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) {
    final boolean sendAsFlowFile = context.getProperty(SEND_AS_FLOWFILE).asBoolean();
    final int compressionLevel = context.getProperty(COMPRESSION_LEVEL).asInteger();
    final String userAgent = context.getProperty(USER_AGENT).getValue();

    final RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();
    requestConfigBuilder.setConnectionRequestTimeout(
            context.getProperty(DATA_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue());
    requestConfigBuilder.setConnectTimeout(
            context.getProperty(CONNECTION_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue());
    requestConfigBuilder.setRedirectsEnabled(false);
    requestConfigBuilder/*  www . j a v a 2s .  c  o  m*/
            .setSocketTimeout(context.getProperty(DATA_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue());
    final RequestConfig requestConfig = requestConfigBuilder.build();

    final StreamThrottler throttler = throttlerRef.get();
    final ComponentLog logger = getLogger();

    final Double maxBatchBytes = context.getProperty(MAX_BATCH_SIZE).asDataSize(DataUnit.B);
    String lastUrl = null;
    long bytesToSend = 0L;

    final List<FlowFile> toSend = new ArrayList<>();
    DestinationAccepts destinationAccepts = null;
    CloseableHttpClient client = null;
    final String transactionId = UUID.randomUUID().toString();

    final AtomicReference<String> dnHolder = new AtomicReference<>("none");
    while (true) {
        FlowFile flowFile = session.get();
        if (flowFile == null) {
            break;
        }

        final String url = context.getProperty(URL).evaluateAttributeExpressions(flowFile).getValue();
        try {
            new java.net.URL(url);
        } catch (final MalformedURLException e) {
            logger.error(
                    "After substituting attribute values for {}, URL is {}; this is not a valid URL, so routing to failure",
                    new Object[] { flowFile, url });
            flowFile = session.penalize(flowFile);
            session.transfer(flowFile, REL_FAILURE);
            continue;
        }

        // If this FlowFile doesn't have the same url, throw it back on the queue and stop grabbing FlowFiles
        if (lastUrl != null && !lastUrl.equals(url)) {
            session.transfer(flowFile);
            break;
        }

        lastUrl = url;
        toSend.add(flowFile);

        if (client == null || destinationAccepts == null) {
            final Config config = getConfig(url, context);
            final HttpClientConnectionManager conMan = config.getConnectionManager();

            final HttpClientBuilder clientBuilder = HttpClientBuilder.create();
            clientBuilder.setConnectionManager(conMan);
            clientBuilder.setUserAgent(userAgent);
            clientBuilder.addInterceptorFirst(new HttpResponseInterceptor() {
                @Override
                public void process(final HttpResponse response, final HttpContext httpContext)
                        throws HttpException, IOException {
                    final HttpCoreContext coreContext = HttpCoreContext.adapt(httpContext);
                    final ManagedHttpClientConnection conn = coreContext
                            .getConnection(ManagedHttpClientConnection.class);
                    if (!conn.isOpen()) {
                        return;
                    }

                    final SSLSession sslSession = conn.getSSLSession();

                    if (sslSession != null) {
                        final Certificate[] certChain = sslSession.getPeerCertificates();
                        if (certChain == null || certChain.length == 0) {
                            throw new SSLPeerUnverifiedException("No certificates found");
                        }

                        try {
                            final X509Certificate cert = CertificateUtils
                                    .convertAbstractX509Certificate(certChain[0]);
                            dnHolder.set(cert.getSubjectDN().getName().trim());
                        } catch (CertificateException e) {
                            final String msg = "Could not extract subject DN from SSL session peer certificate";
                            logger.warn(msg);
                            throw new SSLPeerUnverifiedException(msg);
                        }
                    }
                }
            });

            clientBuilder.disableAutomaticRetries();
            clientBuilder.disableContentCompression();

            final String username = context.getProperty(USERNAME).getValue();
            final String password = context.getProperty(PASSWORD).getValue();
            // set the credentials if appropriate
            if (username != null) {
                final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
                if (password == null) {
                    credentialsProvider.setCredentials(AuthScope.ANY,
                            new UsernamePasswordCredentials(username));
                } else {
                    credentialsProvider.setCredentials(AuthScope.ANY,
                            new UsernamePasswordCredentials(username, password));
                }
                clientBuilder.setDefaultCredentialsProvider(credentialsProvider);
            }

            // Set the proxy if specified
            if (context.getProperty(PROXY_HOST).isSet() && context.getProperty(PROXY_PORT).isSet()) {
                final String host = context.getProperty(PROXY_HOST).getValue();
                final int port = context.getProperty(PROXY_PORT).asInteger();
                clientBuilder.setProxy(new HttpHost(host, port));
            }

            client = clientBuilder.build();

            // determine whether or not destination accepts flowfile/gzip
            destinationAccepts = config.getDestinationAccepts();
            if (destinationAccepts == null) {
                try {
                    destinationAccepts = getDestinationAcceptance(sendAsFlowFile, client, url, getLogger(),
                            transactionId);
                    config.setDestinationAccepts(destinationAccepts);
                } catch (final IOException e) {
                    flowFile = session.penalize(flowFile);
                    session.transfer(flowFile, REL_FAILURE);
                    logger.error(
                            "Unable to communicate with destination {} to determine whether or not it can accept "
                                    + "flowfiles/gzip; routing {} to failure due to {}",
                            new Object[] { url, flowFile, e });
                    context.yield();
                    return;
                }
            }
        }

        bytesToSend += flowFile.getSize();
        if (bytesToSend > maxBatchBytes.longValue()) {
            break;
        }

        // if we are not sending as flowfile, or if the destination doesn't accept V3 or V2 (streaming) format,
        // then only use a single FlowFile
        if (!sendAsFlowFile
                || !destinationAccepts.isFlowFileV3Accepted() && !destinationAccepts.isFlowFileV2Accepted()) {
            break;
        }
    }

    if (toSend.isEmpty()) {
        return;
    }

    final String url = lastUrl;
    final HttpPost post = new HttpPost(url);
    final List<FlowFile> flowFileList = toSend;
    final DestinationAccepts accepts = destinationAccepts;
    final boolean isDestinationLegacyNiFi = accepts.getProtocolVersion() == null;

    final EntityTemplate entity = new EntityTemplate(new ContentProducer() {
        @Override
        public void writeTo(final OutputStream rawOut) throws IOException {
            final OutputStream throttled = throttler == null ? rawOut
                    : throttler.newThrottledOutputStream(rawOut);
            OutputStream wrappedOut = new BufferedOutputStream(throttled);
            if (compressionLevel > 0 && accepts.isGzipAccepted()) {
                wrappedOut = new GZIPOutputStream(wrappedOut, compressionLevel);
            }

            try (final OutputStream out = wrappedOut) {
                for (final FlowFile flowFile : flowFileList) {
                    session.read(flowFile, new InputStreamCallback() {
                        @Override
                        public void process(final InputStream rawIn) throws IOException {
                            try (final InputStream in = new BufferedInputStream(rawIn)) {

                                FlowFilePackager packager = null;
                                if (!sendAsFlowFile) {
                                    packager = null;
                                } else if (accepts.isFlowFileV3Accepted()) {
                                    packager = new FlowFilePackagerV3();
                                } else if (accepts.isFlowFileV2Accepted()) {
                                    packager = new FlowFilePackagerV2();
                                } else if (accepts.isFlowFileV1Accepted()) {
                                    packager = new FlowFilePackagerV1();
                                }

                                // if none of the above conditions is met, we should never get here, because
                                // we will have already verified that at least 1 of the FlowFile packaging
                                // formats is acceptable if sending as FlowFile.
                                if (packager == null) {
                                    StreamUtils.copy(in, out);
                                } else {
                                    final Map<String, String> flowFileAttributes;
                                    if (isDestinationLegacyNiFi) {
                                        // Old versions of NiFi expect nf.file.name and nf.file.path to indicate filename & path;
                                        // in order to maintain backward compatibility, we copy the filename & path to those attribute keys.
                                        flowFileAttributes = new HashMap<>(flowFile.getAttributes());
                                        flowFileAttributes.put("nf.file.name",
                                                flowFile.getAttribute(CoreAttributes.FILENAME.key()));
                                        flowFileAttributes.put("nf.file.path",
                                                flowFile.getAttribute(CoreAttributes.PATH.key()));
                                    } else {
                                        flowFileAttributes = flowFile.getAttributes();
                                    }

                                    packager.packageFlowFile(in, out, flowFileAttributes, flowFile.getSize());
                                }
                            }
                        }
                    });
                }

                out.flush();
            }
        }
    }) {

        @Override
        public long getContentLength() {
            if (compressionLevel == 0 && !sendAsFlowFile
                    && !context.getProperty(CHUNKED_ENCODING).asBoolean()) {
                return toSend.get(0).getSize();
            } else {
                return -1;
            }
        }
    };

    if (context.getProperty(CHUNKED_ENCODING).isSet()) {
        entity.setChunked(context.getProperty(CHUNKED_ENCODING).asBoolean());
    }
    post.setEntity(entity);
    post.setConfig(requestConfig);

    final String contentType;
    if (sendAsFlowFile) {
        if (accepts.isFlowFileV3Accepted()) {
            contentType = APPLICATION_FLOW_FILE_V3;
        } else if (accepts.isFlowFileV2Accepted()) {
            contentType = APPLICATION_FLOW_FILE_V2;
        } else if (accepts.isFlowFileV1Accepted()) {
            contentType = APPLICATION_FLOW_FILE_V1;
        } else {
            logger.error(
                    "Cannot send data to {} because the destination does not accept FlowFiles and this processor is "
                            + "configured to deliver FlowFiles; rolling back session",
                    new Object[] { url });
            session.rollback();
            context.yield();
            IOUtils.closeQuietly(client);
            return;
        }
    } else {
        final String contentTypeValue = context.getProperty(CONTENT_TYPE)
                .evaluateAttributeExpressions(toSend.get(0)).getValue();
        contentType = StringUtils.isBlank(contentTypeValue) ? DEFAULT_CONTENT_TYPE : contentTypeValue;
    }

    final String attributeHeaderRegex = context.getProperty(ATTRIBUTES_AS_HEADERS_REGEX).getValue();
    if (attributeHeaderRegex != null && !sendAsFlowFile && flowFileList.size() == 1) {
        final Pattern pattern = Pattern.compile(attributeHeaderRegex);

        final Map<String, String> attributes = flowFileList.get(0).getAttributes();
        for (final Map.Entry<String, String> entry : attributes.entrySet()) {
            final String key = entry.getKey();
            if (pattern.matcher(key).matches()) {
                post.setHeader(entry.getKey(), entry.getValue());
            }
        }
    }

    post.setHeader(CONTENT_TYPE_HEADER, contentType);
    post.setHeader(FLOWFILE_CONFIRMATION_HEADER, "true");
    post.setHeader(PROTOCOL_VERSION_HEADER, PROTOCOL_VERSION);
    post.setHeader(TRANSACTION_ID_HEADER, transactionId);
    if (compressionLevel > 0 && accepts.isGzipAccepted()) {
        if (sendAsFlowFile) {
            post.setHeader(GZIPPED_HEADER, "true");
        } else {
            post.setHeader(CONTENT_ENCODING_HEADER, CONTENT_ENCODING_GZIP_VALUE);
        }
    }

    // Do the actual POST
    final String flowFileDescription = toSend.size() <= 10 ? toSend.toString() : toSend.size() + " FlowFiles";

    final String uploadDataRate;
    final long uploadMillis;
    CloseableHttpResponse response = null;
    try {
        final StopWatch stopWatch = new StopWatch(true);
        response = client.execute(post);

        // consume input stream entirely, ignoring its contents. If we
        // don't do this, the Connection will not be returned to the pool
        EntityUtils.consume(response.getEntity());
        stopWatch.stop();
        uploadDataRate = stopWatch.calculateDataRate(bytesToSend);
        uploadMillis = stopWatch.getDuration(TimeUnit.MILLISECONDS);
    } catch (final IOException e) {
        logger.error("Failed to Post {} due to {}; transferring to failure",
                new Object[] { flowFileDescription, e });
        context.yield();
        for (FlowFile flowFile : toSend) {
            flowFile = session.penalize(flowFile);
            session.transfer(flowFile, REL_FAILURE);
        }
        return;
    } finally {
        if (response != null) {
            try {
                response.close();
            } catch (final IOException e) {
                getLogger().warn("Failed to close HTTP Response due to {}", new Object[] { e });
            }
        }
    }

    // If we get a 'SEE OTHER' status code and an HTTP header that indicates that the intent
    // of the Location URI is a flowfile hold, we will store this holdUri. This prevents us
    // from posting to some other webservice and then attempting to delete some resource to which
    // we are redirected
    final int responseCode = response.getStatusLine().getStatusCode();
    final String responseReason = response.getStatusLine().getReasonPhrase();
    String holdUri = null;
    if (responseCode == HttpServletResponse.SC_SEE_OTHER) {
        final Header locationUriHeader = response.getFirstHeader(LOCATION_URI_INTENT_NAME);
        if (locationUriHeader != null) {
            if (LOCATION_URI_INTENT_VALUE.equals(locationUriHeader.getValue())) {
                final Header holdUriHeader = response.getFirstHeader(LOCATION_HEADER_NAME);
                if (holdUriHeader != null) {
                    holdUri = holdUriHeader.getValue();
                }
            }
        }

        if (holdUri == null) {
            for (FlowFile flowFile : toSend) {
                flowFile = session.penalize(flowFile);
                logger.error(
                        "Failed to Post {} to {}: sent content and received status code {}:{} but no Hold URI",
                        new Object[] { flowFile, url, responseCode, responseReason });
                session.transfer(flowFile, REL_FAILURE);
            }
            return;
        }
    }

    if (holdUri == null) {
        if (responseCode == HttpServletResponse.SC_SERVICE_UNAVAILABLE) {
            for (FlowFile flowFile : toSend) {
                flowFile = session.penalize(flowFile);
                logger.error(
                        "Failed to Post {} to {}: response code was {}:{}; will yield processing, "
                                + "since the destination is temporarily unavailable",
                        new Object[] { flowFile, url, responseCode, responseReason });
                session.transfer(flowFile, REL_FAILURE);
            }
            context.yield();
            return;
        }

        if (responseCode >= 300) {
            for (FlowFile flowFile : toSend) {
                flowFile = session.penalize(flowFile);
                logger.error("Failed to Post {} to {}: response code was {}:{}",
                        new Object[] { flowFile, url, responseCode, responseReason });
                session.transfer(flowFile, REL_FAILURE);
            }
            return;
        }

        logger.info("Successfully Posted {} to {} in {} at a rate of {}", new Object[] { flowFileDescription,
                url, FormatUtils.formatMinutesSeconds(uploadMillis, TimeUnit.MILLISECONDS), uploadDataRate });

        for (final FlowFile flowFile : toSend) {
            session.getProvenanceReporter().send(flowFile, url, "Remote DN=" + dnHolder.get(), uploadMillis,
                    true);
            session.transfer(flowFile, REL_SUCCESS);
        }
        return;
    }

    //
    // the response indicated a Hold URI; delete the Hold.
    //
    // determine the full URI of the Flow File's Hold; Unfortunately, the responses that are returned have
    // changed over the past, so we have to take into account a few different possibilities.
    String fullHoldUri = holdUri;
    if (holdUri.startsWith("/contentListener")) {
        // If the Hold URI that we get starts with /contentListener, it may not really be /contentListener,
        // as this really indicates that it should be whatever we posted to -- if posting directly to the
        // ListenHTTP component, it will be /contentListener, but if posting to a proxy/load balancer, we may
        // be posting to some other URL.
        fullHoldUri = url + holdUri.substring(16);
    } else if (holdUri.startsWith("/")) {
        // URL indicates the full path but not hostname or port; use the same hostname & port that we posted
        // to but use the full path indicated by the response.
        int firstSlash = url.indexOf("/", 8);
        if (firstSlash < 0) {
            firstSlash = url.length();
        }
        final String beforeSlash = url.substring(0, firstSlash);
        fullHoldUri = beforeSlash + holdUri;
    } else if (!holdUri.startsWith("http")) {
        // Absolute URL
        fullHoldUri = url + (url.endsWith("/") ? "" : "/") + holdUri;
    }

    final HttpDelete delete = new HttpDelete(fullHoldUri);
    delete.setHeader(TRANSACTION_ID_HEADER, transactionId);

    while (true) {
        try {
            final HttpResponse holdResponse = client.execute(delete);
            EntityUtils.consume(holdResponse.getEntity());
            final int holdStatusCode = holdResponse.getStatusLine().getStatusCode();
            final String holdReason = holdResponse.getStatusLine().getReasonPhrase();
            if (holdStatusCode >= 300) {
                logger.error(
                        "Failed to delete Hold that destination placed on {}: got response code {}:{}; routing to failure",
                        new Object[] { flowFileDescription, holdStatusCode, holdReason });

                for (FlowFile flowFile : toSend) {
                    flowFile = session.penalize(flowFile);
                    session.transfer(flowFile, REL_FAILURE);
                }
                return;
            }

            logger.info("Successfully Posted {} to {} in {} milliseconds at a rate of {}",
                    new Object[] { flowFileDescription, url, uploadMillis, uploadDataRate });

            for (final FlowFile flowFile : toSend) {
                session.getProvenanceReporter().send(flowFile, url);
                session.transfer(flowFile, REL_SUCCESS);
            }
            return;
        } catch (final IOException e) {
            logger.warn("Failed to delete Hold that destination placed on {} due to {}",
                    new Object[] { flowFileDescription, e });
        }

        if (!isScheduled()) {
            context.yield();
            logger.warn(
                    "Failed to delete Hold that destination placed on {}; Processor has been stopped so routing FlowFile(s) to failure",
                    new Object[] { flowFileDescription });
            for (FlowFile flowFile : toSend) {
                flowFile = session.penalize(flowFile);
                session.transfer(flowFile, REL_FAILURE);
            }
            return;
        }
    }
}

From source file:org.apache.hadoop.security.ssl.TestReloadingX509KeyManager.java

@Test(timeout = 4000)
public void testReloadCorruptedKeyStore() throws Exception {
    KeyPair keyPair = KeyStoreTestUtil.generateKeyPair(KEY_PAIR_ALGORITHM);
    X509Certificate cert = KeyStoreTestUtil.generateCertificate("CN=cert", keyPair, 2, CERTIFICATE_ALGORITHM);
    String keyStoreLocation = Paths.get(BASE_DIR, "testKeystore.jks").toString();
    KeyStoreTestUtil.createKeyStore(keyStoreLocation, KEYSTORE_PASSWORD, "cert", keyPair.getPrivate(), cert);

    ReloadingX509KeyManager keyManager = new ReloadingX509KeyManager("jks", keyStoreLocation, KEYSTORE_PASSWORD,
            KEYSTORE_PASSWORD, 10, TimeUnit.MILLISECONDS);

    try {//from   w w  w . j  av  a 2  s .c o m
        keyManager.init();
        X509Certificate[] certChain = keyManager.getCertificateChain("cert");
        assertNotNull("Certificate chain should not be null for alias cert", certChain);

        keyManager.getReloadTimeUnit().sleep(keyManager.getReloadInterval());
        TimeUnit.SECONDS.sleep(1);

        FileOutputStream outputStream = new FileOutputStream(keyStoreLocation);
        outputStream.write("something".getBytes());
        outputStream.close();

        keyManager.getReloadTimeUnit().sleep(keyManager.getReloadInterval());
        TimeUnit.SECONDS.sleep(1);

        certChain = keyManager.getCertificateChain("cert");
        assertNotNull("Certificate chain should not be null for alias cert", certChain);
        assertEquals("DN for cert should be CN=cert", cert.getSubjectDN().getName(),
                certChain[0].getSubjectDN().getName());
        List<ScheduledFuture> reloadTasks = KeyManagersReloaderThreadPool.getInstance(true).getListOfTasks();
        // Reloading thread should have been cancelled after unsuccessful reload
        for (ScheduledFuture task : reloadTasks) {
            assertTrue(task.isCancelled());
        }
        assertEquals(KeyManagersReloaderThreadPool.MAX_NUMBER_OF_RETRIES + 1, keyManager.getNumberOfFailures());
    } finally {
        keyManager.stop();
    }
}