Example usage for java.security.cert CertificateFactory generateCertificate

List of usage examples for java.security.cert CertificateFactory generateCertificate

Introduction

In this page you can find the example usage for java.security.cert CertificateFactory generateCertificate.

Prototype

public final Certificate generateCertificate(InputStream inStream) throws CertificateException 

Source Link

Document

Generates a certificate object and initializes it with the data read from the input stream inStream .

Usage

From source file:XmldapCertsAndKeys.java

public static X509Certificate getXmldapCert() throws CertificateException {
    String certB64 = "MIIDXTCCAkUCBEQd+4EwDQYJKoZIhvcNAQEEBQAwczELMAkGA1UEBhMCVVMxEzARBgNVBAgTCkNh"
            + "bGlmb3JuaWExFjAUBgNVBAcTDVNhbiBGcmFuY2lzY28xDzANBgNVBAoTBnhtbGRhcDERMA8GA1UE"
            + "CxMIaW5mb2NhcmQxEzARBgNVBAMTCnhtbGRhcC5vcmcwHhcNMDYwMzIwMDA0NjU3WhcNMDYwNjE4"
            + "MDA0NjU3WjBzMQswCQYDVQQGEwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTEWMBQGA1UEBxMNU2Fu"
            + "IEZyYW5jaXNjbzEPMA0GA1UEChMGeG1sZGFwMREwDwYDVQQLEwhpbmZvY2FyZDETMBEGA1UEAxMK"
            + "eG1sZGFwLm9yZzCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBANMnkVA4xfpG0bLos9FO"
            + "pNBjHAdFahy2cJ7FUwuXd/IShnG+5qF/z1SdPWzRxTtpFFyodtXlBUEIbiT+IbYPZF1vCcBrcFa8"
            + "Kz/4rBjrpPZgllgA/WSVKjnJvw8q4/tO6CQZSlRlj/ebNK9VyT1kN+MrKV1SGTqaIJ2l+7Rd05WH"
            + "scwZMPdVWBbRrg76YTfy6H/NlQIArNLZanPvE0Vd5QfD4ZyG2hTh3y7ZlJAUndGJ/kfZw8sKuL9Q"
            + "Srh4eOTc280NQUmPGz6LP5MXNmu0RxEcomod1+ToKll90yEKFAUKuPYFgm9J+vYm4tzRequLy/nj"
            + "teRIkcfAdcAtt6PCYjUCAwEAATANBgkqhkiG9w0BAQQFAAOCAQEAURtxiA7qDSq/WlUpWpfWiZ7H"
            + "vveQrwTaTwV/Fk3l/I9e9WIRN51uFLuiLtZMMwR02BX7Yva1KQ/Gl999cm/0b5hptJ+TU29rVPZI"
            + "lI32c5vjcuSVoEda8+BRj547jlC0rNokyWm+YtBcDOwfHSPFFwVPPVxyQsVEebsiB6KazFq6iZ8A"
            + "0F2HLEnpsdFnGrSwBBbH3I3PH65ofrTTgj1Mjk5kA6EVaeefDCtlkX2ogIFMlcS6ruihX2mlCLUS"
            + "rlPs9TH+M4j/R/LV5QWJ93/X9gsxFrxVFGg3b75EKQP8MZ111/jaeKd80mUOAiTO06EtfjXZPrjP"
            + "N4e2l05i2EGDUA==";
    byte[] certBytes = Base64.decode(certB64);
    CertificateFactory cf = CertificateFactory.getInstance("X509");
    ByteArrayInputStream inStream = new ByteArrayInputStream(certBytes);
    return (X509Certificate) cf.generateCertificate(inStream);
}

From source file:org.guanxi.idp.service.SSOBase.java

/**
 * Extracts the X509 cenrtificate from a KeyDescriptor
 *
 * @param keyDescriptor the KeyDescriptor containing the X509 certificate
 * @return X509Certificate//from  w  w w  .  j av a2  s. c o m
 * @throws GuanxiException if an error occurs
 */
private X509Certificate getCertFromKeyDescriptor(KeyDescriptorType keyDescriptor) throws GuanxiException {
    try {
        byte[] spCertBytes = keyDescriptor.getKeyInfo().getX509DataArray(0).getX509CertificateArray(0);
        CertificateFactory certFactory = CertificateFactory.getInstance("x.509");
        ByteArrayInputStream certByteStream = new ByteArrayInputStream(spCertBytes);
        X509Certificate metadataCert = (X509Certificate) certFactory.generateCertificate(certByteStream);
        certByteStream.close();
        return metadataCert;
    } catch (CertificateException ce) {
        logger.error("can't get x509 from KeyDescriptor");
        throw new GuanxiException(ce);
    } catch (IOException ioe) {
        logger.error("can't close cert byte stream");
        throw new GuanxiException(ioe);
    }
}

From source file:com.cloudbees.jenkins.plugins.enterpriseplugins.CloudBeesUpdateSite.java

/**
 * Verifies the signature in the update center data file.
 *//*  w  w w.j  a  v  a  2 s .  c o  m*/
private FormValidation verifySignature(JSONObject o) throws IOException {
    try {
        FormValidation warning = null;

        JSONObject signature = o.getJSONObject("signature");
        if (signature.isNullObject()) {
            return FormValidation.error("No signature block found in update center '" + getId() + "'");
        }
        o.remove("signature");

        List<X509Certificate> certs = new ArrayList<X509Certificate>();
        {// load and verify certificates
            CertificateFactory cf = CertificateFactory.getInstance("X509");
            for (Object cert : signature.getJSONArray("certificates")) {
                X509Certificate c = (X509Certificate) cf.generateCertificate(
                        new ByteArrayInputStream(Base64.decode(cert.toString().toCharArray())));
                try {
                    c.checkValidity();
                } catch (CertificateExpiredException e) { // even if the certificate isn't valid yet,
                    // we'll proceed it anyway
                    warning = FormValidation.warning(e, String.format(
                            "Certificate %s has expired in update center '%s'", cert.toString(), getId()));
                } catch (CertificateNotYetValidException e) {
                    warning = FormValidation.warning(e, String.format(
                            "Certificate %s is not yet valid in update center '%s'", cert.toString(), getId()));
                }
                certs.add(c);
            }

            // all default root CAs in JVM are trusted, plus certs bundled in Jenkins
            Set<TrustAnchor> anchors = new HashSet<TrustAnchor>(); // CertificateUtil.getDefaultRootCAs();
            ServletContext context = Hudson.getInstance().servletContext;
            anchors.add(new TrustAnchor(loadLicenseCaCertificate(), null));
            for (String cert : (Set<String>) context.getResourcePaths("/WEB-INF/update-center-rootCAs")) {
                if (cert.endsWith(".txt")) {
                    continue; // skip text files that are meant to be documentation
                }
                InputStream stream = context.getResourceAsStream(cert);
                if (stream != null) {
                    try {
                        anchors.add(new TrustAnchor((X509Certificate) cf.generateCertificate(stream), null));
                    } finally {
                        IOUtils.closeQuietly(stream);
                    }
                }
            }
            CertificateUtil.validatePath(certs, anchors);
        }

        // this is for computing a digest to check sanity
        MessageDigest sha1 = MessageDigest.getInstance("SHA1");
        DigestOutputStream dos = new DigestOutputStream(new NullOutputStream(), sha1);

        // this is for computing a signature
        Signature sig = Signature.getInstance("SHA1withRSA");
        sig.initVerify(certs.get(0));
        SignatureOutputStream sos = new SignatureOutputStream(sig);

        // until JENKINS-11110 fix, UC used to serve invalid digest (and therefore unverifiable signature)
        // that only covers the earlier portion of the file. This was caused by the lack of close() call
        // in the canonical writing, which apparently leave some bytes somewhere that's not flushed to
        // the digest output stream. This affects Jenkins [1.424,1,431].
        // Jenkins 1.432 shipped with the "fix" (1eb0c64abb3794edce29cbb1de50c93fa03a8229) that made it
        // compute the correct digest, but it breaks all the existing UC json metadata out there. We then
        // quickly discovered ourselves in the catch-22 situation. If we generate UC with the correct signature,
        // it'll cut off [1.424,1.431] from the UC. But if we don't, we'll cut off [1.432,*).
        //
        // In 1.433, we revisited 1eb0c64abb3794edce29cbb1de50c93fa03a8229 so that the original "digest"/"signature"
        // pair continues to be generated in a buggy form, while "correct_digest"/"correct_signature" are generated
        // correctly.
        //
        // Jenkins should ignore "digest"/"signature" pair. Accepting it creates a vulnerability that allows
        // the attacker to inject a fragment at the end of the json.
        o.writeCanonical(new OutputStreamWriter(new TeeOutputStream(dos, sos), "UTF-8")).close();

        // did the digest match? this is not a part of the signature validation, but if we have a bug in the c14n
        // (which is more likely than someone tampering with update center), we can tell
        String computedDigest = new String(Base64.encode(sha1.digest()));
        String providedDigest = signature.optString("correct_digest");
        if (providedDigest == null) {
            return FormValidation.error("No correct_digest parameter in update center '" + getId()
                    + "'. This metadata appears to be old.");
        }
        if (!computedDigest.equalsIgnoreCase(providedDigest)) {
            return FormValidation.error("Digest mismatch: " + computedDigest + " vs " + providedDigest
                    + " in update center '" + getId() + "'");
        }

        String providedSignature = signature.getString("correct_signature");
        if (!sig.verify(Base64.decode(providedSignature.toCharArray()))) {
            return FormValidation.error(
                    "Signature in the update center doesn't match with the certificate in update center '"
                            + getId() + "'");
        }

        if (warning != null) {
            return warning;
        }
        return FormValidation.ok();
    } catch (GeneralSecurityException e) {
        return FormValidation.error(e, "Signature verification failed in the update center '" + getId() + "'");
    }
}

From source file:org.codice.ddf.security.certificate.keystore.editor.KeystoreEditor.java

private boolean importASN1CertificatesToStore(KeyStore store, boolean setEntry, ASN1Set certificates)
        throws KeystoreEditorException {
    Enumeration certificateEnumeration = certificates.getObjects();
    try {/*from   w ww .ja va2  s  .co m*/
        while (certificateEnumeration.hasMoreElements()) {
            ASN1Primitive asn1Primitive = ((ASN1Encodable) certificateEnumeration.nextElement())
                    .toASN1Primitive();
            org.bouncycastle.asn1.x509.Certificate instance = org.bouncycastle.asn1.x509.Certificate
                    .getInstance(asn1Primitive);
            CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509", "BC");
            Certificate certificate = certificateFactory
                    .generateCertificate(new ByteArrayInputStream(instance.getEncoded()));
            X500Name x500name = new JcaX509CertificateHolder((X509Certificate) certificate).getSubject();
            RDN cn = x500name.getRDNs(BCStyle.CN)[0];
            store.setCertificateEntry(IETFUtils.valueToString(cn.getFirst().getValue()), certificate);
            setEntry = true;
        }
    } catch (CertificateException | NoSuchProviderException | KeyStoreException | IOException e) {
        throw new KeystoreEditorException("Unable to import ASN1 certificates to store", e);
    }
    return setEntry;
}

From source file:org.apache.jk.server.JkCoyoteHandler.java

public void action(ActionCode actionCode, Object param) {
    try {/*  w w w. java2 s. c om*/
        if (actionCode == ActionCode.ACTION_COMMIT) {
            if (log.isDebugEnabled())
                log.debug("COMMIT ");
            org.apache.coyote.Response res = (org.apache.coyote.Response) param;

            if (res.isCommitted()) {
                if (log.isInfoEnabled())
                    log.info("Response already commited ");
            } else {
                appendHead(res);
            }
        } else if (actionCode == ActionCode.ACTION_RESET) {
            if (log.isDebugEnabled())
                log.debug("RESET ");

        } else if (actionCode == ActionCode.ACTION_CLIENT_FLUSH) {
            if (log.isDebugEnabled())
                log.debug("CLIENT_FLUSH ");
            org.apache.coyote.Response res = (org.apache.coyote.Response) param;
            MsgContext ep = (MsgContext) res.getNote(epNote);
            ep.setType(JkHandler.HANDLE_FLUSH);
            ep.getSource().invoke(null, ep);

        } else if (actionCode == ActionCode.ACTION_CLOSE) {
            if (log.isDebugEnabled())
                log.debug("CLOSE ");

            org.apache.coyote.Response res = (org.apache.coyote.Response) param;
            MsgContext ep = (MsgContext) res.getNote(epNote);
            if (ep.getStatus() == JK_STATUS_CLOSED) {
                // Double close - it may happen with forward 
                if (log.isDebugEnabled())
                    log.debug("Double CLOSE - forward ? " + res.getRequest().requestURI());
                return;
            }

            if (!res.isCommitted())
                this.action(ActionCode.ACTION_COMMIT, param);

            MsgAjp msg = (MsgAjp) ep.getNote(headersMsgNote);
            msg.reset();
            msg.appendByte(HandlerRequest.JK_AJP13_END_RESPONSE);
            msg.appendByte(1);

            ep.setType(JkHandler.HANDLE_SEND_PACKET);
            ep.getSource().invoke(msg, ep);

            ep.setType(JkHandler.HANDLE_FLUSH);
            ep.getSource().invoke(msg, ep);

            ep.setStatus(JK_STATUS_CLOSED);

            if (logTime.isDebugEnabled())
                logTime(res.getRequest(), res);
        } else if (actionCode == ActionCode.ACTION_REQ_SSL_ATTRIBUTE) {
            org.apache.coyote.Request req = (org.apache.coyote.Request) param;

            // Extract SSL certificate information (if requested)
            MessageBytes certString = (MessageBytes) req.getNote(WorkerEnv.SSL_CERT_NOTE);
            if (certString != null && !certString.isNull()) {
                ByteChunk certData = certString.getByteChunk();
                ByteArrayInputStream bais = new ByteArrayInputStream(certData.getBytes(), certData.getStart(),
                        certData.getLength());

                // Fill the first element.
                X509Certificate jsseCerts[] = null;
                try {
                    CertificateFactory cf = CertificateFactory.getInstance("X.509");
                    X509Certificate cert = (X509Certificate) cf.generateCertificate(bais);
                    jsseCerts = new X509Certificate[1];
                    jsseCerts[0] = cert;
                } catch (java.security.cert.CertificateException e) {
                    log.error("Certificate convertion failed", e);
                    return;
                }

                req.setAttribute(SSLSupport.CERTIFICATE_KEY, jsseCerts);
            }

        } else if (actionCode == ActionCode.ACTION_REQ_HOST_ATTRIBUTE) {
            org.apache.coyote.Request req = (org.apache.coyote.Request) param;

            // If remoteHost not set by JK, get it's name from it's remoteAddr
            if (req.remoteHost().isNull())
                req.remoteHost().setString(InetAddress.getByName(req.remoteAddr().toString()).getHostName());

            // } else if( actionCode==ActionCode.ACTION_POST_REQUEST ) {

        } else if (actionCode == ActionCode.ACTION_ACK) {
            if (log.isDebugEnabled())
                log.debug("ACK ");
            // What should we do here ? Who calls it ? 
        }
    } catch (Exception ex) {
        log.error("Error in action code ", ex);
    }
}

From source file:com.evilisn.DAO.CertMapper.java

@Override
public Object mapRow(ResultSet resultSet, int i) throws SQLException {
    Cert crt = new Cert();
    crt.setCertificate(resultSet.getString("certificate"));
    CertificateFactory fact = null;
    try {/*from   w  ww  . ja v a2  s. c o m*/
        fact = CertificateFactory.getInstance("X.509");
    } catch (CertificateException e) {
        e.printStackTrace();
    }
    X509Certificate x509cert = null;
    InputStream stream = new ByteArrayInputStream(crt.getCertificate().getBytes(StandardCharsets.UTF_8));
    try {
        x509cert = (X509Certificate) fact.generateCertificate(stream);
        crt.setClient_cert(x509cert);
    } catch (CertificateException e) {
        e.printStackTrace();
    }
    crt.setResponder_uri(OCSP.getResponderURI(x509cert));
    X509Certificate issuerCert;
    if (!cached_issuers.containsKey(getIssuerCertURL(x509cert))) {
        //download and set the issuers.
        try {
            issuerCert = getX509Certificate(httpGetBin(getIssuerCertURL(x509cert), true));
            cached_issuers.put(getIssuerCertURL(x509cert), issuerCert);
            crt.setIssuer_cert(issuerCert);
        } catch (Exception e) {
            e.printStackTrace();
        }
    } else {
        issuerCert = cached_issuers.get(getIssuerCertURL(x509cert));
        crt.setIssuer_cert(issuerCert);
    }

    Principal principal = x509cert.getIssuerDN();
    String issuerDn = principal.getName();
    crt.setIssuer_dn(issuerDn);
    return crt;
}

From source file:net.lightbody.bmp.proxy.jetty.http.ajp.AJP13Connection.java

public boolean handleNext() {
    AJP13RequestPacket packet = null;/*from  w w  w .  j av  a  2 s .  c  o m*/
    HttpRequest request = getRequest();
    HttpResponse response = getResponse();
    HttpContext context = null;
    boolean gotRequest = false;
    _persistent = true;
    _keepAlive = true;

    try {
        try {
            packet = null;
            packet = _ajpIn.nextPacket();
            if (packet == null)
                return false;
            if (packet.getDataSize() == 0)
                return true;
        } catch (IOException e) {
            LogSupport.ignore(log, e);
            return false;
        }

        int type = packet.getByte();
        if (log.isDebugEnabled())
            log.debug("AJP13 type=" + type + " size=" + packet.unconsumedData());

        switch (type) {
        case AJP13Packet.__FORWARD_REQUEST:
            request.setTimeStamp(System.currentTimeMillis());

            request.setState(HttpMessage.__MSG_EDITABLE);
            request.setMethod(packet.getMethod());
            request.setVersion(packet.getString());
            String version = packet.getString();
            try {
                request.setVersion(version);
            } catch (Exception e) {
                log.warn("Bad version" + version, e);
                log.warn(packet.toString());
            }

            String path = packet.getString();
            int sc = path.lastIndexOf(";");
            if (sc < 0)
                request.setPath(URI.encodePath(path));
            else
                request.setPath(URI.encodePath(path.substring(0, sc)) + path.substring(sc));

            _remoteAddr = packet.getString();
            _remoteHost = packet.getString();
            _serverName = packet.getString();
            _serverPort = packet.getInt();
            _isSSL = packet.getBoolean();

            // Check keep alive
            _keepAlive = request.getDotVersion() >= 1;

            // Headers
            int h = packet.getInt();
            for (int i = 0; i < h; i++) {
                String hdr = packet.getHeader();
                String val = packet.getString();
                request.addField(hdr, val);
                if (!_keepAlive && hdr.equalsIgnoreCase(HttpFields.__Connection)
                        && val.equalsIgnoreCase(HttpFields.__KeepAlive))
                    _keepAlive = true;
            }

            // Handler other attributes
            byte attr = packet.getByte();
            while ((0xFF & attr) != 0xFF) {
                String value = (attr == 11) ? null : packet.getString();
                switch (attr) {
                case 11: // key size
                    request.setAttribute("javax.servlet.request.key_size", new Integer(packet.getInt()));
                    break;
                case 10: // request attribute
                    request.setAttribute(value, packet.getString());
                    break;
                case 9: // SSL session
                    request.setAttribute("javax.servlet.request.ssl_session", value);
                    break;
                case 8: // SSL cipher
                    request.setAttribute("javax.servlet.request.cipher_suite", value);
                    break;
                case 7: // SSL cert
                    // request.setAttribute("javax.servlet.request.X509Certificate",value);
                    CertificateFactory cf = CertificateFactory.getInstance("X.509");
                    InputStream certstream = new ByteArrayInputStream(value.getBytes());
                    X509Certificate cert = (X509Certificate) cf.generateCertificate(certstream);
                    X509Certificate certs[] = { cert };
                    request.setAttribute("javax.servlet.request.X509Certificate", certs);
                    break;
                case 6: // JVM Route
                    request.setAttribute("net.lightbody.bmp.proxy.jetty.http.ajp.JVMRoute", value);
                    break;
                case 5: // Query String
                    request.setQuery(value);
                    break;
                case 4: // AuthType
                    request.setAuthType(value);
                    break;
                case 3: // Remote User
                    request.setAuthUser(value);
                    break;

                case 2: // servlet path not implemented
                case 1: // _context not implemented
                default:
                    log.warn("Unknown attr: " + attr + "=" + value);
                }

                attr = packet.getByte();
            }

            _listener.customizeRequest(this, request);

            gotRequest = true;
            statsRequestStart();
            request.setState(HttpMessage.__MSG_RECEIVED);

            // Complete response
            if (request.getContentLength() == 0 && request.getField(HttpFields.__TransferEncoding) == null)
                _ajpIn.close();

            // Prepare response
            response.setState(HttpMessage.__MSG_EDITABLE);
            response.setVersion(HttpMessage.__HTTP_1_1);
            response.setDateField(HttpFields.__Date, _request.getTimeStamp());
            if (!Version.isParanoid())
                response.setField(HttpFields.__Server, Version.getDetail());

            // Service request
            if (log.isDebugEnabled())
                log.debug("REQUEST:\n" + request);
            context = service(request, response);
            if (log.isDebugEnabled())
                log.debug("RESPONSE:\n" + response);

            break;

        default:
            if (log.isDebugEnabled())
                log.debug("Ignored: " + packet);
            _persistent = false;
        }

    } catch (SocketException e) {
        LogSupport.ignore(log, e);
        _persistent = false;
    } catch (Exception e) {
        log.warn(LogSupport.EXCEPTION, e);
        _persistent = false;
        try {
            if (gotRequest)
                _ajpOut.close();
        } catch (IOException e2) {
            LogSupport.ignore(log, e2);
        }
    } finally {
        // abort if nothing received.
        if (packet == null || !gotRequest)
            return false;

        // flush and end the output
        try {
            // Consume unread input.
            // while(_ajpIn.skip(4096)>0 || _ajpIn.read()>=0);

            // end response
            getOutputStream().close();
            if (!_persistent)
                _ajpOut.end();

            // Close the outout
            _ajpOut.close();

            // reset streams
            getOutputStream().resetStream();
            getOutputStream().addObserver(this);
            getInputStream().resetStream();
            _ajpIn.resetStream();
            _ajpOut.resetStream();
        } catch (Exception e) {
            log.debug(LogSupport.EXCEPTION, e);
            _persistent = false;
        } finally {
            statsRequestEnd();
            if (context != null)
                context.log(request, response, -1);
        }
    }
    return _persistent;
}

From source file:org.browsermob.proxy.jetty.http.ajp.AJP13Connection.java

public boolean handleNext() {
    AJP13RequestPacket packet = null;//w ww  . ja  v a 2s .c o  m
    HttpRequest request = getRequest();
    HttpResponse response = getResponse();
    HttpContext context = null;
    boolean gotRequest = false;
    _persistent = true;
    _keepAlive = true;

    try {
        try {
            packet = null;
            packet = _ajpIn.nextPacket();
            if (packet == null)
                return false;
            if (packet.getDataSize() == 0)
                return true;
        } catch (IOException e) {
            LogSupport.ignore(log, e);
            return false;
        }

        int type = packet.getByte();
        if (log.isDebugEnabled())
            log.debug("AJP13 type=" + type + " size=" + packet.unconsumedData());

        switch (type) {
        case AJP13Packet.__FORWARD_REQUEST:
            request.setTimeStamp(System.currentTimeMillis());

            request.setState(HttpMessage.__MSG_EDITABLE);
            request.setMethod(packet.getMethod());
            request.setVersion(packet.getString());
            String version = packet.getString();
            try {
                request.setVersion(version);
            } catch (Exception e) {
                log.warn("Bad version" + version, e);
                log.warn(packet.toString());
            }

            String path = packet.getString();
            int sc = path.lastIndexOf(";");
            if (sc < 0)
                request.setPath(URI.encodePath(path));
            else
                request.setPath(URI.encodePath(path.substring(0, sc)) + path.substring(sc));

            _remoteAddr = packet.getString();
            _remoteHost = packet.getString();
            _serverName = packet.getString();
            _serverPort = packet.getInt();
            _isSSL = packet.getBoolean();

            // Check keep alive
            _keepAlive = request.getDotVersion() >= 1;

            // Headers
            int h = packet.getInt();
            for (int i = 0; i < h; i++) {
                String hdr = packet.getHeader();
                String val = packet.getString();
                request.addField(hdr, val);
                if (!_keepAlive && hdr.equalsIgnoreCase(HttpFields.__Connection)
                        && val.equalsIgnoreCase(HttpFields.__KeepAlive))
                    _keepAlive = true;
            }

            // Handler other attributes
            byte attr = packet.getByte();
            while ((0xFF & attr) != 0xFF) {
                String value = (attr == 11) ? null : packet.getString();
                switch (attr) {
                case 11: // key size
                    request.setAttribute("javax.servlet.request.key_size", new Integer(packet.getInt()));
                    break;
                case 10: // request attribute
                    request.setAttribute(value, packet.getString());
                    break;
                case 9: // SSL session
                    request.setAttribute("javax.servlet.request.ssl_session", value);
                    break;
                case 8: // SSL cipher
                    request.setAttribute("javax.servlet.request.cipher_suite", value);
                    break;
                case 7: // SSL cert
                    // request.setAttribute("javax.servlet.request.X509Certificate",value);
                    CertificateFactory cf = CertificateFactory.getInstance("X.509");
                    InputStream certstream = new ByteArrayInputStream(value.getBytes());
                    X509Certificate cert = (X509Certificate) cf.generateCertificate(certstream);
                    X509Certificate certs[] = { cert };
                    request.setAttribute("javax.servlet.request.X509Certificate", certs);
                    break;
                case 6: // JVM Route
                    request.setAttribute("org.browsermob.proxy.jetty.http.ajp.JVMRoute", value);
                    break;
                case 5: // Query String
                    request.setQuery(value);
                    break;
                case 4: // AuthType
                    request.setAuthType(value);
                    break;
                case 3: // Remote User
                    request.setAuthUser(value);
                    break;

                case 2: // servlet path not implemented
                case 1: // _context not implemented
                default:
                    log.warn("Unknown attr: " + attr + "=" + value);
                }

                attr = packet.getByte();
            }

            _listener.customizeRequest(this, request);

            gotRequest = true;
            statsRequestStart();
            request.setState(HttpMessage.__MSG_RECEIVED);

            // Complete response
            if (request.getContentLength() == 0 && request.getField(HttpFields.__TransferEncoding) == null)
                _ajpIn.close();

            // Prepare response
            response.setState(HttpMessage.__MSG_EDITABLE);
            response.setVersion(HttpMessage.__HTTP_1_1);
            response.setDateField(HttpFields.__Date, _request.getTimeStamp());
            if (!Version.isParanoid())
                response.setField(HttpFields.__Server, Version.getDetail());

            // Service request
            if (log.isDebugEnabled())
                log.debug("REQUEST:\n" + request);
            context = service(request, response);
            if (log.isDebugEnabled())
                log.debug("RESPONSE:\n" + response);

            break;

        default:
            if (log.isDebugEnabled())
                log.debug("Ignored: " + packet);
            _persistent = false;
        }

    } catch (SocketException e) {
        LogSupport.ignore(log, e);
        _persistent = false;
    } catch (Exception e) {
        log.warn(LogSupport.EXCEPTION, e);
        _persistent = false;
        try {
            if (gotRequest)
                _ajpOut.close();
        } catch (IOException e2) {
            LogSupport.ignore(log, e2);
        }
    } finally {
        // abort if nothing received.
        if (packet == null || !gotRequest)
            return false;

        // flush and end the output
        try {
            // Consume unread input.
            // while(_ajpIn.skip(4096)>0 || _ajpIn.read()>=0);

            // end response
            getOutputStream().close();
            if (!_persistent)
                _ajpOut.end();

            // Close the outout
            _ajpOut.close();

            // reset streams
            getOutputStream().resetStream();
            getOutputStream().addObserver(this);
            getInputStream().resetStream();
            _ajpIn.resetStream();
            _ajpOut.resetStream();
        } catch (Exception e) {
            log.debug(LogSupport.EXCEPTION, e);
            _persistent = false;
        } finally {
            statsRequestEnd();
            if (context != null)
                context.log(request, response, -1);
        }
    }
    return _persistent;
}

From source file:org.openqa.jetty.http.ajp.AJP13Connection.java

public boolean handleNext() {
    AJP13RequestPacket packet = null;//from w w w . j ava 2 s.  c om
    HttpRequest request = getRequest();
    HttpResponse response = getResponse();
    HttpContext context = null;
    boolean gotRequest = false;
    _persistent = true;
    _keepAlive = true;

    try {
        try {
            packet = null;
            packet = _ajpIn.nextPacket();
            if (packet == null)
                return false;
            if (packet.getDataSize() == 0)
                return true;
        } catch (IOException e) {
            LogSupport.ignore(log, e);
            return false;
        }

        int type = packet.getByte();
        if (log.isDebugEnabled())
            log.debug("AJP13 type=" + type + " size=" + packet.unconsumedData());

        switch (type) {
        case AJP13Packet.__FORWARD_REQUEST:
            request.setTimeStamp(System.currentTimeMillis());

            request.setState(HttpMessage.__MSG_EDITABLE);
            request.setMethod(packet.getMethod());
            request.setVersion(packet.getString());
            String version = packet.getString();
            try {
                request.setVersion(version);
            } catch (Exception e) {
                log.warn("Bad version" + version, e);
                log.warn(packet.toString());
            }

            String path = packet.getString();
            int sc = path.lastIndexOf(";");
            if (sc < 0)
                request.setPath(URI.encodePath(path));
            else
                request.setPath(URI.encodePath(path.substring(0, sc)) + path.substring(sc));

            _remoteAddr = packet.getString();
            _remoteHost = packet.getString();
            _serverName = packet.getString();
            _serverPort = packet.getInt();
            _isSSL = packet.getBoolean();

            // Check keep alive
            _keepAlive = request.getDotVersion() >= 1;

            // Headers
            int h = packet.getInt();
            for (int i = 0; i < h; i++) {
                String hdr = packet.getHeader();
                String val = packet.getString();
                request.addField(hdr, val);
                if (!_keepAlive && hdr.equalsIgnoreCase(HttpFields.__Connection)
                        && val.equalsIgnoreCase(HttpFields.__KeepAlive))
                    _keepAlive = true;
            }

            // RestishHandler other attributes
            byte attr = packet.getByte();
            while ((0xFF & attr) != 0xFF) {
                String value = (attr == 11) ? null : packet.getString();
                switch (attr) {
                case 11: // key size
                    request.setAttribute("javax.servlet.request.key_size", new Integer(packet.getInt()));
                    break;
                case 10: // request attribute
                    request.setAttribute(value, packet.getString());
                    break;
                case 9: // SSL session
                    request.setAttribute("javax.servlet.request.ssl_session", value);
                    break;
                case 8: // SSL cipher
                    request.setAttribute("javax.servlet.request.cipher_suite", value);
                    break;
                case 7: // SSL cert
                    // request.setAttribute("javax.servlet.request.X509Certificate",value);
                    CertificateFactory cf = CertificateFactory.getInstance("X.509");
                    InputStream certstream = new ByteArrayInputStream(value.getBytes());
                    X509Certificate cert = (X509Certificate) cf.generateCertificate(certstream);
                    X509Certificate certs[] = { cert };
                    request.setAttribute("javax.servlet.request.X509Certificate", certs);
                    break;
                case 6: // JVM Route
                    request.setAttribute("org.openqa.jetty.http.ajp.JVMRoute", value);
                    break;
                case 5: // Query String
                    request.setQuery(value);
                    break;
                case 4: // AuthType
                    request.setAuthType(value);
                    break;
                case 3: // Remote User
                    request.setAuthUser(value);
                    break;

                case 2: // servlet path not implemented
                case 1: // _context not implemented
                default:
                    log.warn("Unknown attr: " + attr + "=" + value);
                }

                attr = packet.getByte();
            }

            _listener.customizeRequest(this, request);

            gotRequest = true;
            statsRequestStart();
            request.setState(HttpMessage.__MSG_RECEIVED);

            // Complete response
            if (request.getContentLength() == 0 && request.getField(HttpFields.__TransferEncoding) == null)
                _ajpIn.close();

            // Prepare response
            response.setState(HttpMessage.__MSG_EDITABLE);
            response.setVersion(HttpMessage.__HTTP_1_1);
            response.setDateField(HttpFields.__Date, _request.getTimeStamp());
            if (!Version.isParanoid())
                response.setField(HttpFields.__Server, Version.getDetail());

            // Service request
            if (log.isDebugEnabled())
                log.debug("REQUEST:\n" + request);
            context = service(request, response);
            if (log.isDebugEnabled())
                log.debug("RESPONSE:\n" + response);

            break;

        default:
            if (log.isDebugEnabled())
                log.debug("Ignored: " + packet);
            _persistent = false;
        }

    } catch (SocketException e) {
        LogSupport.ignore(log, e);
        _persistent = false;
    } catch (Exception e) {
        log.warn(LogSupport.EXCEPTION, e);
        _persistent = false;
        try {
            if (gotRequest)
                _ajpOut.close();
        } catch (IOException e2) {
            LogSupport.ignore(log, e2);
        }
    } finally {
        // abort if nothing received.
        if (packet == null || !gotRequest)
            return false;

        // flush and end the output
        try {
            // Consume unread input.
            // while(_ajpIn.skip(4096)>0 || _ajpIn.read()>=0);

            // end response
            getOutputStream().close();
            if (!_persistent)
                _ajpOut.end();

            // Close the outout
            _ajpOut.close();

            // reset streams
            getOutputStream().resetStream();
            getOutputStream().addObserver(this);
            getInputStream().resetStream();
            _ajpIn.resetStream();
            _ajpOut.resetStream();
        } catch (Exception e) {
            log.debug(LogSupport.EXCEPTION, e);
            _persistent = false;
        } finally {
            statsRequestEnd();
            if (context != null)
                context.log(request, response, -1);
        }
    }
    return _persistent;
}

From source file:org.apache.cxf.ws.security.sts.provider.operation.IssueDelegateTest.java

@Test
public void testIssueDelegateWithInvalidCert2() throws CertificateException {
    IssueDelegate id = new IssueDelegate();
    assertNotNull(id);//  w  w w  . j  a  va 2s  .c  o  m

    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    X509Certificate x509Certificate = (X509Certificate) certificateFactory
            .generateCertificate(new ByteArrayInputStream(Base64.decodeBase64(CERT_DATA.getBytes())));
    JAXBElement<X509Certificate> jX509Certificate = new JAXBElement<X509Certificate>(
            QName.valueOf("X509Certificate"), X509Certificate.class, x509Certificate);

    // JAXBElement<byte[]> jX509Certificate = new
    // JAXBElement<byte[]>(QName.valueOf("X509Certificate"), byte[].class,
    // CERT_DATA.getBytes());

    X509DataType x509DataType = new X509DataType();
    x509DataType.getX509IssuerSerialOrX509SKIOrX509SubjectName().add(jX509Certificate);
    JAXBElement<X509DataType> jX509DataType = new JAXBElement<X509DataType>(QName.valueOf("X509Data"),
            X509DataType.class, x509DataType);

    KeyInfoType keyInfoType = new KeyInfoType();
    keyInfoType.getContent().add(jX509DataType);
    JAXBElement<KeyInfoType> jKeyInfoType = new JAXBElement<KeyInfoType>(QName.valueOf("KeyInfo"),
            KeyInfoType.class, keyInfoType);

    UseKeyType useKeyType = new UseKeyType();
    useKeyType.setAny(jKeyInfoType);
    JAXBElement<UseKeyType> jUseKeyType = new JAXBElement<UseKeyType>(QName.valueOf("UseKey"), UseKeyType.class,
            useKeyType);

    EasyMock.expect(requestMock.getAny()).andStubReturn(Arrays.asList((Object) jUseKeyType));
    EasyMock.replay(requestMock);

    EasyMock.expect(passwordCallbackMock.resetUsername()).andReturn(null);
    EasyMock.expect(passwordCallbackMock.resetPassword()).andReturn("joespassword");
    EasyMock.replay(passwordCallbackMock);

    TokenProvider tp1 = new Saml1TokenProvider();
    TokenProvider tp2 = new Saml2TokenProvider();
    id.setTokenProviders(Arrays.asList(tp1, tp2));

    id.setPasswordCallback(passwordCallbackMock);

    try {
        id.issue(requestMock);
        fail("CertificateException should be thrown");
    } catch (Exception e) {
    }

    verify(requestMock);
}