Search in sources :

Example 56 with X500Name

use of org.openecard.bouncycastle.asn1.x500.X500Name in project oxTrust by GluuFederation.

the class UpdateTrustRelationshipAction method getCertForGeneratedSP.

/**
 * If there is no certificate selected, or certificate is invalid -
 * generates one.
 *
 * @author �Oleksiy Tataryn�
 * @return certificate for generated SP
 * @throws IOException
 * @throws CertificateEncodingException
 */
public String getCertForGeneratedSP() throws IOException {
    X509Certificate cert = null;
    if ((certWrapper != null) && (certWrapper.getInputStream() != null)) {
        try {
            cert = sslService.getPEMCertificate(certWrapper.getInputStream());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }
    if ((cert == null) && (trustRelationship.getUrl() != null)) {
        facesMessages.add(FacesMessage.SEVERITY_ERROR, "Certificate were not provided, or was incorrect. Appliance will create a self-signed certificate.");
        if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
            Security.addProvider(new BouncyCastleProvider());
        }
        try {
            KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA", "BC");
            keyPairGen.initialize(2048);
            KeyPair pair = keyPairGen.generateKeyPair();
            StringWriter keyWriter = new StringWriter();
            PEMWriter pemFormatWriter = new PEMWriter(keyWriter);
            pemFormatWriter.writeObject(pair.getPrivate());
            pemFormatWriter.close();
            String url = trustRelationship.getUrl().replaceFirst(".*//", "");
            X509v3CertificateBuilder v3CertGen = new JcaX509v3CertificateBuilder(new X500Name("CN=" + url + ", OU=None, O=None L=None, C=None"), BigInteger.valueOf(new SecureRandom().nextInt()), new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30), new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 365 * 10)), new X500Name("CN=" + url + ", OU=None, O=None L=None, C=None"), pair.getPublic());
            cert = new JcaX509CertificateConverter().setProvider("BC").getCertificate(v3CertGen.build(new JcaContentSignerBuilder("MD5withRSA").setProvider("BC").build(pair.getPrivate())));
            org.apache.commons.codec.binary.Base64 encoder = new org.apache.commons.codec.binary.Base64(64);
            byte[] derCert = cert.getEncoded();
            String pemCertPre = new String(encoder.encode(derCert));
            log.debug(Shibboleth3ConfService.PUBLIC_CERTIFICATE_START_LINE);
            log.debug(pemCertPre);
            log.debug(Shibboleth3ConfService.PUBLIC_CERTIFICATE_END_LINE);
            shibboleth3ConfService.saveCert(trustRelationship, pemCertPre);
            shibboleth3ConfService.saveKey(trustRelationship, keyWriter.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    // String certName = appConfiguration.getCertDir() + File.separator + StringHelper.removePunctuation(appConfiguration.getOrgInum())
    // + "-shib.crt";
    // File certFile = new File(certName);
    // if (certFile.exists()) {
    // cert = SSLService.instance().getPEMCertificate(certName);
    // }
    }
    String certificate = null;
    if (cert != null) {
        try {
            certificate = new String(Base64.encode(cert.getEncoded()));
            log.info("##### certificate = " + certificate);
        } catch (CertificateEncodingException e) {
            certificate = null;
            facesMessages.add(FacesMessage.SEVERITY_ERROR, "Failed to encode provided certificate. Please notify Gluu support about this.");
            log.error("Failed to encode certificate to DER", e);
        }
    } else {
        facesMessages.add(FacesMessage.SEVERITY_ERROR, "Certificate were not provided, or was incorrect. Appliance will create a self-signed certificate.");
    }
    return certificate;
}
Also used : KeyPair(java.security.KeyPair) Base64(org.bouncycastle.util.encoders.Base64) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) SecureRandom(java.security.SecureRandom) PEMWriter(org.bouncycastle.openssl.PEMWriter) CertificateEncodingException(java.security.cert.CertificateEncodingException) KeyPairGenerator(java.security.KeyPairGenerator) X500Name(org.bouncycastle.asn1.x500.X500Name) X509Certificate(java.security.cert.X509Certificate) CertificateEncodingException(java.security.cert.CertificateEncodingException) BaseMappingException(org.gluu.persist.exception.mapping.BaseMappingException) IOException(java.io.IOException) Date(java.util.Date) StringWriter(java.io.StringWriter) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider)

Example 57 with X500Name

use of org.openecard.bouncycastle.asn1.x500.X500Name in project oxTrust by GluuFederation.

the class TrustRelationshipWebService method generateCertForGeneratedSP.

/**
 * @return certificate for generated SP
 * @throws IOException
 * @throws CertificateEncodingException
 */
public String generateCertForGeneratedSP(GluuSAMLTrustRelationship trustRelationship) throws IOException {
    X509Certificate cert = null;
    // facesMessages.add(FacesMessage.SEVERITY_ERROR, "Certificate were not provided, or was incorrect. Appliance will create a self-signed certificate.");
    if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
        Security.addProvider(new BouncyCastleProvider());
    }
    try {
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA", "BC");
        keyPairGen.initialize(2048);
        KeyPair pair = keyPairGen.generateKeyPair();
        StringWriter keyWriter = new StringWriter();
        PEMWriter pemFormatWriter = new PEMWriter(keyWriter);
        pemFormatWriter.writeObject(pair.getPrivate());
        pemFormatWriter.close();
        String url = trustRelationship.getUrl().replaceFirst(".*//", "");
        X509v3CertificateBuilder v3CertGen = new JcaX509v3CertificateBuilder(new X500Name("CN=" + url + ", OU=None, O=None L=None, C=None"), BigInteger.valueOf(new SecureRandom().nextInt()), new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30), new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 365 * 10)), new X500Name("CN=" + url + ", OU=None, O=None L=None, C=None"), pair.getPublic());
        cert = new JcaX509CertificateConverter().setProvider("BC").getCertificate(v3CertGen.build(new JcaContentSignerBuilder("MD5withRSA").setProvider("BC").build(pair.getPrivate())));
        org.apache.commons.codec.binary.Base64 encoder = new org.apache.commons.codec.binary.Base64(64);
        byte[] derCert = cert.getEncoded();
        String pemCertPre = new String(encoder.encode(derCert));
        logger.debug(Shibboleth3ConfService.PUBLIC_CERTIFICATE_START_LINE);
        logger.debug(pemCertPre);
        logger.debug(Shibboleth3ConfService.PUBLIC_CERTIFICATE_END_LINE);
        shibboleth3ConfService.saveCert(trustRelationship, pemCertPre);
        shibboleth3ConfService.saveKey(trustRelationship, keyWriter.toString());
    } catch (Exception e) {
        e.printStackTrace();
        logger.error("Failed to generate certificate", e);
    }
    // String certName = appConfiguration.getCertDir() + File.separator + StringHelper.removePunctuation(appConfiguration.getOrgInum())
    // + "-shib.crt";
    // File certFile = new File(certName);
    // if (certFile.exists()) {
    // cert = SSLService.instance().getPEMCertificate(certName);
    // }
    String certificate = null;
    if (cert != null) {
        try {
            certificate = new String(Base64.encode(cert.getEncoded()));
            logger.info("##### certificate = " + certificate);
        } catch (CertificateEncodingException e) {
            certificate = null;
            // facesMessages.add(FacesMessage.SEVERITY_ERROR, "Failed to encode provided certificate. Please notify Gluu support about this.");
            logger.error("Failed to encode certificate to DER", e);
        }
    } else {
    // facesMessages.add(FacesMessage.SEVERITY_ERROR, "Certificate were not provided, or was incorrect. Appliance will create a self-signed certificate.");
    }
    return certificate;
}
Also used : KeyPair(java.security.KeyPair) Base64(org.bouncycastle.util.encoders.Base64) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) SecureRandom(java.security.SecureRandom) PEMWriter(org.bouncycastle.openssl.PEMWriter) CertificateEncodingException(java.security.cert.CertificateEncodingException) KeyPairGenerator(java.security.KeyPairGenerator) X500Name(org.bouncycastle.asn1.x500.X500Name) X509Certificate(java.security.cert.X509Certificate) Date(java.util.Date) CertificateEncodingException(java.security.cert.CertificateEncodingException) BaseMappingException(org.gluu.persist.exception.mapping.BaseMappingException) IOException(java.io.IOException) StringWriter(java.io.StringWriter) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider)

Example 58 with X500Name

use of org.openecard.bouncycastle.asn1.x500.X500Name in project Payara by payara.

the class SecurityMechanismSelector method getIdentity.

/**
 * Get the principal/distinguished name from thread local storage.
 *
 * @return the security context.
 */
private SecurityContext getIdentity() throws SecurityMechanismException {
    if (_logger.isLoggable(Level.FINE)) {
        _logger.log(Level.FINE, "Getting PRINCIPAL/DN from TLS");
    }
    SecurityContext ctx = new SecurityContext();
    final SecurityContext sCtx = ctx;
    // get stuff from the SecurityContext class
    com.sun.enterprise.security.SecurityContext scontext = com.sun.enterprise.security.SecurityContext.getCurrent();
    if ((scontext == null) || scontext.didServerGenerateCredentials()) {
        // a default guest/guest123 was created
        sCtx.identcls = AnonCredential.class;
        AccessController.doPrivileged(new PrivilegedAction<Object>() {

            @Override
            public java.lang.Object run() {
                // remove all the public and private credentials
                Subject sub = new Subject();
                sCtx.subject = sub;
                sCtx.subject.getPublicCredentials().add(new AnonCredential());
                return null;
            }
        });
        return sCtx;
    }
    Subject s = getSubjectFromSecurityCurrent();
    ctx.subject = s;
    // Figure out the credential class
    final Subject sub = s;
    Set<PasswordCredential> credSet = AccessController.doPrivileged(new PrivilegedAction<Set>() {

        @Override
        public Set run() {
            return sub.getPrivateCredentials(PasswordCredential.class);
        }
    });
    if (credSet.size() == 1) {
        ctx.identcls = GSSUPName.class;
        final Set cs = credSet;
        Subject subj = AccessController.doPrivileged(new PrivilegedAction<Subject>() {

            @Override
            public Subject run() {
                Subject ss = new Subject();
                Iterator<PasswordCredential> iter = cs.iterator();
                PasswordCredential pc = iter.next();
                GSSUPName gssname = new GSSUPName(pc.getUser(), pc.getRealm());
                ss.getPublicCredentials().add(gssname);
                return ss;
            }
        });
        ctx.subject = subj;
        return ctx;
    }
    Set pubCredSet = s.getPublicCredentials();
    if (pubCredSet.size() != 1) {
        _logger.log(Level.SEVERE, "iiop.principal_error");
        return null;
    } else {
        Iterator credIter = pubCredSet.iterator();
        if (credIter.hasNext()) {
            Object o = credIter.next();
            if (o instanceof GSSUPName) {
                ctx.identcls = GSSUPName.class;
            } else if (o instanceof X500Name) {
                ctx.identcls = X500Name.class;
            } else {
                ctx.identcls = X509CertificateCredential.class;
            }
        } else {
            _logger.log(Level.SEVERE, "iiop.credential_error");
            return null;
        }
    }
    return ctx;
}
Also used : Set(java.util.Set) HashSet(java.util.HashSet) PasswordCredential(com.sun.enterprise.security.auth.login.common.PasswordCredential) X500Name(sun.security.x509.X500Name) Subject(javax.security.auth.Subject) GSSUPName(com.sun.enterprise.common.iiop.security.GSSUPName) X509CertificateCredential(com.sun.enterprise.security.auth.login.common.X509CertificateCredential) ClientSecurityContext(com.sun.enterprise.security.common.ClientSecurityContext) SecurityContext(com.sun.enterprise.common.iiop.security.SecurityContext) Iterator(java.util.Iterator) AnonCredential(com.sun.enterprise.common.iiop.security.AnonCredential)

Example 59 with X500Name

use of org.openecard.bouncycastle.asn1.x500.X500Name in project Payara by payara.

the class JarSigner method signJar.

/**
 * Signs a JAR, adding caller-specified attributes to the manifest's main attrs and also
 * inserting (and signing) additional caller-supplied content as new entries in the
 * zip output stream.
 * @param input input JAR file
 * @param zout Zip output stream created
 * @param alias signing alias in the keystore
 * @param additionalAttrs additional attributes to add to the manifest's main attrs (null if none)
 * @param additionalEntries entry-name/byte[] pairs of additional content to add to the signed output
 * @throws IOException
 * @throws KeyStoreException
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeyException
 * @throws UnrecoverableKeyException
 * @throws SignatureException
 */
public void signJar(File input, ZipOutputStream zout, String alias, final Attributes additionalAttrs, Map<String, byte[]> additionalEntries) throws IOException, KeyStoreException, NoSuchAlgorithmException, InvalidKeyException, UnrecoverableKeyException, SignatureException {
    JarFile jf = new JarFile(input);
    try {
        Enumeration<JarEntry> jes;
        // manifestEntries is content of META-INF/MANIFEST.MF
        StringBuilder manifestEntries = new StringBuilder();
        byte[] manifestContent;
        byte[] sigFileContent = getExistingSignatureFile(jf);
        boolean signed = (sigFileContent != null);
        if (!signed || !additionalEntries.isEmpty()) {
            // manifestHeader is header of META-INF/MANIFEST.MF, initialized to default
            jes = jf.entries();
            Manifest manifest = retrieveManifest(jf);
            StringBuilder manifestHeader = new StringBuilder();
            Attributes mfAttrs = manifest.getMainAttributes();
            if (additionalAttrs != null) {
                mfAttrs.putAll(additionalAttrs);
            }
            appendAttributes(manifestHeader, mfAttrs);
            // sigFileEntries is content of META-INF/ME.SF
            StringBuilder sigFileEntries = new StringBuilder();
            while (jes.hasMoreElements()) {
                JarEntry je = jes.nextElement();
                String name = je.getName();
                if ((je.isDirectory() && manifest.getAttributes(name) == null) || name.equals(JarFile.MANIFEST_NAME)) {
                    continue;
                }
                processMetadataForEntry(manifest, manifestEntries, sigFileEntries, name, readJarEntry(jf, je));
            }
            if (additionalEntries != null) {
                for (Map.Entry<String, byte[]> entry : additionalEntries.entrySet()) {
                    processMetadataForEntry(manifest, manifestEntries, sigFileEntries, entry.getKey(), entry.getValue());
                }
            }
            // META-INF/ME.SF
            StringBuilder sigFile = new StringBuilder("Signature-Version: 1.0\r\n").append(digestAlgorithm).append("-Digest-Manifest-Main-Attributes: ").append(hash(manifestHeader.toString())).append("\r\n").append("Created-By: ").append(System.getProperty("java.version")).append(" (").append(System.getProperty("java.vendor")).append(")\r\n");
            // Combine header and content of MANIFEST.MF, and rehash
            manifestHeader.append(manifestEntries);
            sigFile.append(digestAlgorithm).append("-Digest-Manifest: ").append(hash(manifestHeader.toString())).append("\r\n\r\n");
            // Combine header and content of ME.SF
            sigFile.append(sigFileEntries);
            manifestContent = manifestHeader.toString().getBytes();
            sigFileContent = sigFile.toString().getBytes();
        } else {
            manifestContent = readJarEntry(jf, jf.getJarEntry(JarFile.MANIFEST_NAME));
        }
        X509Certificate[] certChain = null;
        PrivateKey privKey = null;
        KeyStore[] ks = securitySupport.getKeyStores();
        for (int i = 0; i < ks.length; i++) {
            privKey = securitySupport.getPrivateKeyForAlias(alias, i);
            if (privKey != null) {
                Certificate[] cs = ks[i].getCertificateChain(alias);
                certChain = new X509Certificate[cs.length];
                for (int j = 0; j < cs.length; j++) {
                    certChain[j] = (X509Certificate) cs[j];
                }
            }
        }
        // Sign ME.SF
        Signature sig = Signature.getInstance(digestAlgorithm + "with" + keyAlgorithm);
        sig.initSign(privKey);
        sig.update(sigFileContent);
        // Create PKCS7 block
        PKCS7 pkcs7 = new PKCS7(new AlgorithmId[] { AlgorithmId.get(digestAlgorithm) }, new ContentInfo(sigFileContent), certChain, new SignerInfo[] { new SignerInfo((X500Name) certChain[0].getIssuerDN(), certChain[0].getSerialNumber(), AlgorithmId.get(digestAlgorithm), AlgorithmId.get(keyAlgorithm), sig.sign()) });
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        pkcs7.encodeSignedData(bout);
        // Write output
        zout.putNextEntry((signed) ? getZipEntry(jf.getJarEntry(JarFile.MANIFEST_NAME)) : new ZipEntry(JarFile.MANIFEST_NAME));
        zout.write(manifestContent);
        zout.putNextEntry(new ZipEntry("META-INF/" + alias.toUpperCase(Locale.US) + ".SF"));
        zout.write(sigFileContent);
        zout.putNextEntry(new ZipEntry("META-INF/" + alias.toUpperCase(Locale.US) + "." + keyAlgorithm));
        zout.write(bout.toByteArray());
        jes = jf.entries();
        while (jes.hasMoreElements()) {
            JarEntry je = jes.nextElement();
            String name = je.getName();
            if (!name.equals(JarFile.MANIFEST_NAME)) {
                zout.putNextEntry(getZipEntry(je));
                byte[] data = readJarEntry(jf, je);
                zout.write(data);
            }
        }
        if (additionalEntries != null) {
            for (Map.Entry<String, byte[]> entry : additionalEntries.entrySet()) {
                final ZipEntry newZipEntry = new ZipEntry(entry.getKey());
                zout.putNextEntry(newZipEntry);
                zout.write(entry.getValue());
            }
        }
    } finally {
        jf.close();
    }
}
Also used : PrivateKey(java.security.PrivateKey) ZipEntry(java.util.zip.ZipEntry) Attributes(java.util.jar.Attributes) X500Name(sun.security.x509.X500Name) ContentInfo(sun.security.pkcs.ContentInfo) PKCS7(sun.security.pkcs.PKCS7) ByteArrayOutputStream(java.io.ByteArrayOutputStream) JarFile(java.util.jar.JarFile) JarEntry(java.util.jar.JarEntry) Manifest(java.util.jar.Manifest) KeyStore(java.security.KeyStore) X509Certificate(java.security.cert.X509Certificate) SignerInfo(sun.security.pkcs.SignerInfo) Signature(java.security.Signature) Map(java.util.Map) Collections.emptyMap(java.util.Collections.emptyMap) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 60 with X500Name

use of org.openecard.bouncycastle.asn1.x500.X500Name in project Payara by payara.

the class LoginContextDriver method jmacLogin.

public static Subject jmacLogin(Subject subject, X500Principal x500Principal) throws LoginException {
    if (subject == null) {
        subject = new Subject();
    }
    final Subject fs = subject;
    String userName = "";
    try {
        final X500Name x500Name = new X500Name(x500Principal.getName(X500Principal.RFC1779));
        userName = x500Name.toString();
        AppservAccessController.doPrivileged(new PrivilegedAction() {

            public java.lang.Object run() {
                fs.getPublicCredentials().add(x500Name);
                return fs;
            }
        });
        Realm realm = Realm.getInstance(CertificateRealm.AUTH_TYPE);
        CertificateRealm certRealm = (CertificateRealm) realm;
        String jaasCtx = certRealm.getJAASContext();
        if (jaasCtx != null) {
            // The subject has the Cretificate Credential.
            LoginContext lg = new LoginContext(jaasCtx, fs, dummyCallback);
            lg.login();
        }
        certRealm.authenticate(fs, x500Name);
    } catch (Exception ex) {
        if (_logger.isLoggable(Level.INFO)) {
            _logger.log(Level.INFO, SecurityLoggerInfo.auditAtnRefusedError, userName);
        }
        if (getAuditManager().isAuditOn()) {
            getAuditManager().authentication(userName, CertificateRealm.AUTH_TYPE, false);
        }
        if (ex instanceof LoginException) {
            throw (LoginException) ex;
        } else {
            throw (LoginException) new LoginException(ex.toString()).initCause(ex);
        }
    }
    if (_logger.isLoggable(Level.FINE)) {
        _logger.fine("jmac cert login succeeded for: " + userName);
    }
    if (getAuditManager().isAuditOn()) {
        getAuditManager().authentication(userName, CertificateRealm.AUTH_TYPE, true);
    }
    return subject;
}
Also used : LoginContext(javax.security.auth.login.LoginContext) PrivilegedAction(java.security.PrivilegedAction) LoginException(com.sun.enterprise.security.auth.login.common.LoginException) X500Name(sun.security.x509.X500Name) CertificateRealm(com.sun.enterprise.security.auth.realm.certificate.CertificateRealm) Realm(com.sun.enterprise.security.auth.realm.Realm) CertificateRealm(com.sun.enterprise.security.auth.realm.certificate.CertificateRealm) Subject(javax.security.auth.Subject) LoginException(com.sun.enterprise.security.auth.login.common.LoginException) NoSuchRealmException(com.sun.enterprise.security.auth.realm.NoSuchRealmException) InvalidOperationException(com.sun.enterprise.security.auth.realm.InvalidOperationException) NoSuchUserException(com.sun.enterprise.security.auth.realm.NoSuchUserException)

Aggregations

X500Name (org.bouncycastle.asn1.x500.X500Name)193 X509Certificate (java.security.cert.X509Certificate)88 Date (java.util.Date)71 BigInteger (java.math.BigInteger)63 X500Name (sun.security.x509.X500Name)53 IOException (java.io.IOException)49 JcaContentSignerBuilder (org.bouncycastle.operator.jcajce.JcaContentSignerBuilder)47 ContentSigner (org.bouncycastle.operator.ContentSigner)45 X509v3CertificateBuilder (org.bouncycastle.cert.X509v3CertificateBuilder)44 RDN (org.bouncycastle.asn1.x500.RDN)43 JcaX509CertificateConverter (org.bouncycastle.cert.jcajce.JcaX509CertificateConverter)42 KeyPair (java.security.KeyPair)41 X509CertificateHolder (org.bouncycastle.cert.X509CertificateHolder)41 SubjectPublicKeyInfo (org.bouncycastle.asn1.x509.SubjectPublicKeyInfo)36 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)33 PrivateKey (java.security.PrivateKey)32 KeyPairGenerator (java.security.KeyPairGenerator)31 GeneralName (org.bouncycastle.asn1.x509.GeneralName)31 DERUTF8String (org.bouncycastle.asn1.DERUTF8String)28 SecureRandom (java.security.SecureRandom)27