Search in sources :

Example 1 with SecurityException

use of com.emc.storageos.security.exceptions.SecurityException in project coprhd-controller by CoprHD.

the class CassandraTokenManager method getToken.

/**
 * Persist/Update the StorageOSUserDAO record
 * generates a new token or reuses an existing token.
 *
 * @return token as a String
 */
@Override
public String getToken(StorageOSUserDAO userDAO) {
    try {
        // always use lower case username for comparing/saving to db
        userDAO.setUserName(userDAO.getUserName().toLowerCase());
        // find an active user record, if there is one with an active token
        List<StorageOSUserDAO> userRecords = getUserRecords(userDAO.getUserName());
        StorageOSUserDAO user = updateDBWithUser(userDAO, userRecords);
        // do we have a user account to use?
        if (user == null) {
            // No, create one
            userDAO.setId(URIUtil.createId(StorageOSUserDAO.class));
            _dbClient.persistObject(userDAO);
            user = userDAO;
        } else {
            // check count
            List<Token> tokensForUserId = getTokensForUserId(user.getId());
            int maxTokens = user.getUserName().equalsIgnoreCase(PROXY_USER) ? _maxTokensForProxyUser : _maxTokensPerUserId;
            double alertTokensSize = (maxTokens * TOKEN_WARNING_EIGHTY_PERCENT);
            if (tokensForUserId.size() >= maxTokens) {
                throw APIException.unauthorized.maxNumberOfTokenExceededForUser();
            } else if (tokensForUserId.size() == (int) alertTokensSize) {
                _log.warn("Prior to creating new token, user {} had {} tokens.", user.getUserName(), tokensForUserId.size());
            }
        }
        return _tokenEncoder.encode(TokenOnWire.createTokenOnWire(createNewToken(user)));
    } catch (DatabaseException ex) {
        _log.error("Exception while persisting user information {}", userDAO.getUserName(), ex);
    } catch (SecurityException e) {
        _log.error("Token encoding exception. ", e);
    }
    return null;
}
Also used : StorageOSUserDAO(com.emc.storageos.db.client.model.StorageOSUserDAO) ProxyToken(com.emc.storageos.db.client.model.ProxyToken) Token(com.emc.storageos.db.client.model.Token) SecurityException(com.emc.storageos.security.exceptions.SecurityException) DatabaseException(com.emc.storageos.db.exceptions.DatabaseException) DecommissionedConstraint(com.emc.storageos.db.client.constraint.DecommissionedConstraint)

Example 2 with SecurityException

use of com.emc.storageos.security.exceptions.SecurityException in project coprhd-controller by CoprHD.

the class KeyCertificatePairGeneratorTest method testVerifyKeyCertificateEntry.

@Test
public void testVerifyKeyCertificateEntry() {
    KeyCertificatePairGenerator gen = new KeyCertificatePairGenerator();
    gen.setKeyCertificateAlgorithmValuesHolder(defaultValues);
    // test a generated entry
    KeyCertificateEntry entry1 = gen.generateKeyCertificatePair();
    try {
        new KeyCertificatePairGenerator().verifyKeyCertificateEntry(entry1);
    } catch (SecurityException e) {
        System.err.println(e.getMessage());
        System.err.println(e);
        Assert.fail();
    } catch (BadRequestException e) {
        System.err.println(e.getMessage());
        System.err.println(e);
        Assert.fail();
    }
    // test values from 2 different generated entries
    KeyCertificateEntry entry2 = gen.generateKeyCertificatePair();
    KeyCertificateEntry hybridEntry = new KeyCertificateEntry(entry1.getKey(), entry2.getCertificateChain());
    boolean exceptionThrown = false;
    try {
        new KeyCertificatePairGenerator().verifyKeyCertificateEntry(hybridEntry);
    } catch (SecurityException e) {
        Assert.fail();
    } catch (BadRequestException e) {
        exceptionThrown = true;
    }
    Assert.assertTrue(exceptionThrown);
}
Also used : KeyCertificatePairGenerator(com.emc.storageos.security.keystore.impl.KeyCertificatePairGenerator) BadRequestException(com.emc.storageos.svcs.errorhandling.resources.BadRequestException) GeneralSecurityException(java.security.GeneralSecurityException) SecurityException(com.emc.storageos.security.exceptions.SecurityException) KeyCertificateEntry(com.emc.storageos.security.keystore.impl.KeyCertificateEntry) Test(org.junit.Test)

Example 3 with SecurityException

use of com.emc.storageos.security.exceptions.SecurityException in project coprhd-controller by CoprHD.

the class Base64TokenEncoder method decode.

/**
 * base64 decodes the supplied String into a SignedToken object, extracts the signature,
 * deserializes the TokenOnWire object and reads its key id. Fetches the key id from the
 * key generator. Computes a signature based on the fetched key and the serialized token.
 * Compares the resulting signature to the one included in the SignedToken object. If
 * they don't match, throw. if they do, return the deserialized TokenOnWire object.
 *
 * @throws SecurityException
 */
@Override
public TokenOnWire decode(String encodedToken) throws SecurityException {
    try {
        // if encoding is disabled, just parse the string as a token id directly
        if (_tokenEncodingDisabler != null) {
            return new TokenOnWire(URI.create(encodedToken));
        }
        // decode the bytes from the string
        byte[] decoded = Base64.decodeBase64(encodedToken.getBytes("UTF-8"));
        // Get the signedtoken object from the decoded bytes.
        SignedToken st = _serializer.fromByteArray(SignedToken.class, decoded);
        // deserialize the TokenOnWire object
        TokenOnWire tw = _serializer.fromByteArray(TokenOnWire.class, st.getTokenBody());
        // At this point, we know if this token was issued by this VDC or not.
        // If not our VDC, check the cache for keys, if not found, make a request.
        SecretKey foreignKey = null;
        String vdcId = URIUtil.parseVdcIdFromURI(tw.getTokenId());
        if (vdcId == null) {
            _log.info("Old token from ViPR 1.1 - treating token as local");
        } else if (!tw.isProxyToken() && !VdcUtil.getLocalShortVdcId().equals(vdcId)) {
            foreignKey = getForeignKey(tw, encodedToken);
        } else {
            _log.info("Token VDCid {} matches that of this VDC {}", vdcId, VdcUtil.getLocalShortVdcId());
        }
        // get the key id that the token was encoded with
        String key = tw.getEncryptionKeyId();
        // fetch the corresponding key from the key generator. if the key has been rotated out, we are done.
        SecretKey skey = foreignKey == null ? _keyGenerator.getTokenSignatureKey(key) : foreignKey;
        if (skey == null) {
            String error = String.format("The key id %s provided in the token could not be matched to secret key", key);
            _log.error(error);
            throw SecurityException.fatals.keyIDCouldNotBeMatchedToSecretKey(key);
        }
        // The key is still present in the system. Compute a signature with the fetched key against
        // the body of the supplied token
        String signatureFromToken = st._signature;
        String computedSignature = SignatureHelper.sign2(st._tokenBody, skey, TOKEN_SIGNING_ALGO);
        // compare the computed signature against the supplied one.
        if (!signatureFromToken.equals(computedSignature)) {
            String error = String.format("The signature on the provided token does not validate");
            _log.error(error);
            throw APIException.unauthorized.unableToDecodeTokenTheSignatureDoesNotValidate();
        }
        return tw;
    } catch (Exception ex) {
        throw APIException.unauthorized.unableToDecodeToken(ex);
    }
}
Also used : SecretKey(javax.crypto.SecretKey) APIException(com.emc.storageos.svcs.errorhandling.resources.APIException) SecurityException(com.emc.storageos.security.exceptions.SecurityException)

Example 4 with SecurityException

use of com.emc.storageos.security.exceptions.SecurityException in project coprhd-controller by CoprHD.

the class LogoutHandlingFilter method doFilter.

@Override
public void doFilter(final ServletRequest servletRequest, final ServletResponse servletResponse, final FilterChain filterChain) throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) servletRequest;
    if (!findLogoutPattern(req.getRequestURI())) {
        filterChain.doFilter(servletRequest, servletResponse);
    } else {
        // logout request, handle here
        URI endpoint = null;
        try {
            endpoint = _endpointLocator.getAnEndpoint();
        } catch (SecurityException e) {
            final HttpServletResponse response = (HttpServletResponse) servletResponse;
            response.sendError(toHTTPStatus(e), toServiceErrorXml(e));
        }
        StringBuilder redirectURL = new StringBuilder(endpoint.toString());
        if (!InetAddresses.isInetAddress(endpoint.getHost()) || RequestProcessingUtils.getTokenFromCookie(req) != null) {
            // ok, then, keep them on the same node
            redirectURL = RequestProcessingUtils.getOnNodeAuthsvcRedirectURL(req, endpoint);
        }
        redirectURL.append("/logout");
        String queryString = SecurityUtils.stripXSS(req.getQueryString());
        if (queryString != null && !queryString.isEmpty()) {
            redirectURL.append("?" + queryString);
        }
        _logger.info("redirecting logout request: url: {}", redirectURL.toString());
        final HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.sendRedirect(redirectURL.toString());
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpServletResponse(javax.servlet.http.HttpServletResponse) SecurityException(com.emc.storageos.security.exceptions.SecurityException) URI(java.net.URI)

Example 5 with SecurityException

use of com.emc.storageos.security.exceptions.SecurityException in project coprhd-controller by CoprHD.

the class KeystoreTest method testKeystoreEngine.

@Test
public void testKeystoreEngine() throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException, InterruptedException, UnrecoverableEntryException {
    DistributedKeyStore zookeeperKeystore = new DistributedKeyStoreImpl();
    zookeeperKeystore.init(loadStoreParam);
    // this is in case this test was run previously
    zookeeperKeystore.setTrustedCertificates(null);
    zookeeperKeystore.setKeyCertificatePair(null);
    // test keystore loading
    KeyStore ks = KeyStore.getInstance(SecurityProvider.KEYSTORE_TYPE, new SecurityProvider());
    boolean exceptionThrown = false;
    try {
        ks.load(null, null);
    } catch (SecurityException e) {
        Assert.assertEquals(ServiceCode.SECURITY_ERROR, e.getServiceCode());
        Assert.assertEquals("Could not initialize the keystore. The ViPR keystore can only be initialized with a LoadKeyStoreParam.", e.getMessage());
        exceptionThrown = true;
    }
    Assert.assertTrue(exceptionThrown);
    exceptionThrown = false;
    try {
        ks.load(invalidLoadStoreParam);
    } catch (SecurityException e) {
        Assert.assertEquals(ServiceCode.SECURITY_ERROR, e.getServiceCode());
        Assert.assertEquals("Could not initialize the keystore. The ViPR keystore can only be initialized with a LoadKeyStoreParam.", e.getMessage());
        exceptionThrown = true;
    }
    Assert.assertTrue(exceptionThrown);
    // now it shouldn't throw
    ks.load(loadStoreParam);
    // ////////////////////////////////////////////////////////////////////////
    // /
    // / key tests
    // /
    // ////////////////////////////////////////////////////////////////////////
    // should have by default the ViPR key
    List<String> expectedAliases = new ArrayList<String>();
    expectedAliases.add(KeystoreEngine.ViPR_KEY_AND_CERTIFICATE_ALIAS);
    assertAliasesIn(ks, expectedAliases);
    // update the vipr key using ks.setEntry
    Date beforeDate = new Date();
    KeyCertificateEntry entry = gen.generateKeyCertificatePair();
    KeyStore.PrivateKeyEntry privateKeyEntry = new PrivateKeyEntry(KeyCertificatePairGenerator.loadPrivateKeyFromBytes(entry.getKey()), entry.getCertificateChain());
    KeyStore.PasswordProtection empryProtectionParam = new KeyStore.PasswordProtection("".toCharArray());
    ks.setEntry(KeystoreEngine.ViPR_KEY_AND_CERTIFICATE_ALIAS, privateKeyEntry, new KeyStore.PasswordProtection("123".toCharArray()));
    Date afterDate = new Date();
    assertKeyCertificateEntryEquals(ks, entry);
    assertCreationDateInTImeRange(ks, KeystoreEngine.ViPR_KEY_AND_CERTIFICATE_ALIAS, beforeDate, afterDate);
    // set the key entry using setKeyEntry (there are 2 versions, one with the Key
    // object, and another with byte[] )
    beforeDate = new Date();
    entry = gen.generateKeyCertificatePair();
    ks.setKeyEntry(KeystoreEngine.ViPR_KEY_AND_CERTIFICATE_ALIAS, entry.getKey(), entry.getCertificateChain());
    afterDate = new Date();
    assertKeyCertificateEntryEquals(ks, entry);
    assertCreationDateInTImeRange(ks, KeystoreEngine.ViPR_KEY_AND_CERTIFICATE_ALIAS, beforeDate, afterDate);
    beforeDate = new Date();
    entry = gen.generateKeyCertificatePair();
    ks.setKeyEntry(KeystoreEngine.ViPR_KEY_AND_CERTIFICATE_ALIAS, KeyCertificatePairGenerator.loadPrivateKeyFromBytes(entry.getKey()), "".toCharArray(), entry.getCertificateChain());
    afterDate = new Date();
    assertKeyCertificateEntryEquals(ks, entry);
    assertCreationDateInTImeRange(ks, KeystoreEngine.ViPR_KEY_AND_CERTIFICATE_ALIAS, beforeDate, afterDate);
    // ////////////////////////////////////////////////////////////////////////
    // /
    // / certificates tests
    // /
    // ////////////////////////////////////////////////////////////////////////
    String certAlias = "someCert";
    // add a new trusted certificate using ks.setEntry
    beforeDate = new Date();
    entry = gen.generateKeyCertificatePair();
    KeyStore.TrustedCertificateEntry trustedCertEntry = new KeyStore.TrustedCertificateEntry(entry.getCertificateChain()[0]);
    ks.setEntry(certAlias, trustedCertEntry, null);
    afterDate = new Date();
    expectedAliases.add(certAlias);
    assertAliasesIn(ks, expectedAliases);
    assertTrustedCertEquals(ks, entry, certAlias);
    assertCreationDateInTImeRange(ks, certAlias, beforeDate, afterDate);
    // add a new trusted certificate using ks.setCertificateEntry
    beforeDate = new Date();
    entry = gen.generateKeyCertificatePair();
    certAlias = "someCert1";
    ks.setCertificateEntry(certAlias, entry.getCertificateChain()[0]);
    afterDate = new Date();
    expectedAliases.add(certAlias);
    assertAliasesIn(ks, expectedAliases);
    assertTrustedCertEquals(ks, entry, certAlias);
    assertCreationDateInTImeRange(ks, certAlias, beforeDate, afterDate);
    // remove the trusted certificate entry
    ks.deleteEntry(certAlias);
    expectedAliases.remove(certAlias);
    assertAliasesIn(ks, expectedAliases);
    // ////////////////////////////////////////////////////////////////////////
    // /
    // / Negative testing
    // /
    // ////////////////////////////////////////////////////////////////////////
    String invalidEntryName = "invalidEntry";
    // cannot delete the ViPR key
    exceptionThrown = false;
    try {
        ks.deleteEntry(KeystoreEngine.ViPR_KEY_AND_CERTIFICATE_ALIAS);
    } catch (SecurityException e) {
        Assert.assertEquals(ServiceCode.SECURITY_ERROR, e.getServiceCode());
        Assert.assertEquals("The ViPR key and certificate cannot be deleted, it can only be updated.", e.getMessage());
        exceptionThrown = true;
    } catch (KeyStoreException e) {
        Assert.fail();
    }
    Assert.assertTrue(exceptionThrown);
    assertAliasesIn(ks, expectedAliases);
    entry = gen.generateKeyCertificatePair();
    // try to set a key that is not the vipr key
    // using ks.setEntry
    privateKeyEntry = new PrivateKeyEntry(KeyCertificatePairGenerator.loadPrivateKeyFromBytes(entry.getKey()), entry.getCertificateChain());
    exceptionThrown = false;
    try {
        ks.setEntry(invalidEntryName, privateKeyEntry, empryProtectionParam);
    } catch (SecurityException e) {
        Assert.assertEquals(ServiceCode.SECURITY_ERROR, e.getServiceCode());
        Assert.assertEquals("Cannot update any key and certificate entry except for the ViPR key and certificate.", e.getMessage());
        exceptionThrown = true;
    }
    Assert.assertTrue(exceptionThrown);
    assertAliasesIn(ks, expectedAliases);
    // using ks.setKey which accepts byte[]
    try {
        ks.setKeyEntry(invalidEntryName, entry.getKey(), entry.getCertificateChain());
    } catch (SecurityException e) {
        Assert.assertEquals(ServiceCode.SECURITY_ERROR, e.getServiceCode());
        Assert.assertEquals("Cannot update any key and certificate entry except for the ViPR key and certificate.", e.getMessage());
        exceptionThrown = true;
    }
    Assert.assertTrue(exceptionThrown);
    assertAliasesIn(ks, expectedAliases);
    // using ks.setKey which accepts Key object
    try {
        ks.setKeyEntry(invalidEntryName, KeyCertificatePairGenerator.loadPrivateKeyFromBytes(entry.getKey()), "".toCharArray(), entry.getCertificateChain());
    } catch (SecurityException e) {
        Assert.assertEquals(ServiceCode.SECURITY_ERROR, e.getServiceCode());
        Assert.assertEquals("Cannot update any key and certificate entry except for the ViPR key and certificate.", e.getMessage());
        exceptionThrown = true;
    }
    Assert.assertTrue(exceptionThrown);
    assertAliasesIn(ks, expectedAliases);
    // try getting an invalid entry
    Assert.assertFalse(ks.containsAlias(invalidEntryName));
    Assert.assertFalse(ks.entryInstanceOf(invalidEntryName, KeyStore.TrustedCertificateEntry.class));
    Assert.assertFalse(ks.entryInstanceOf(invalidEntryName, KeyStore.PrivateKeyEntry.class));
    Assert.assertFalse(ks.entryInstanceOf(invalidEntryName, KeyStore.SecretKeyEntry.class));
    Assert.assertFalse(ks.isCertificateEntry(invalidEntryName));
    Assert.assertFalse(ks.isKeyEntry(invalidEntryName));
    Assert.assertNull(ks.getCertificate(invalidEntryName));
    Assert.assertNull(ks.getCertificateAlias(entry.getCertificateChain()[0]));
    Assert.assertNull(ks.getCertificateChain(invalidEntryName));
    Assert.assertNull(ks.getCreationDate(invalidEntryName));
    Assert.assertNull(ks.getEntry(invalidEntryName, empryProtectionParam));
    Assert.assertNull(ks.getKey(invalidEntryName, "".toCharArray()));
    // try to delete an entry that does not exist
    exceptionThrown = false;
    try {
        ks.deleteEntry(invalidEntryName);
    } catch (SecurityException e) {
        Assert.fail();
    } catch (KeyStoreException e) {
        exceptionThrown = true;
        Assert.assertEquals("The specified alias " + invalidEntryName + " does not exist", e.getMessage());
    }
    Assert.assertTrue(exceptionThrown);
}
Also used : ArrayList(java.util.ArrayList) SecurityException(com.emc.storageos.security.exceptions.SecurityException) KeyStoreException(java.security.KeyStoreException) KeyStore(java.security.KeyStore) Date(java.util.Date) KeyCertificateEntry(com.emc.storageos.security.keystore.impl.KeyCertificateEntry) PrivateKeyEntry(java.security.KeyStore.PrivateKeyEntry) TrustedCertificateEntry(com.emc.storageos.security.keystore.impl.TrustedCertificateEntry) DistributedKeyStoreImpl(com.emc.storageos.security.keystore.impl.DistributedKeyStoreImpl) SecurityProvider(com.emc.storageos.security.keystore.impl.SecurityProvider) PrivateKeyEntry(java.security.KeyStore.PrivateKeyEntry) Test(org.junit.Test)

Aggregations

SecurityException (com.emc.storageos.security.exceptions.SecurityException)8 ProxyToken (com.emc.storageos.db.client.model.ProxyToken)3 DatabaseException (com.emc.storageos.db.exceptions.DatabaseException)3 KeyCertificateEntry (com.emc.storageos.security.keystore.impl.KeyCertificateEntry)3 Test (org.junit.Test)3 Token (com.emc.storageos.db.client.model.Token)2 DistributedKeyStoreImpl (com.emc.storageos.security.keystore.impl.DistributedKeyStoreImpl)2 TrustedCertificateEntry (com.emc.storageos.security.keystore.impl.TrustedCertificateEntry)2 APIException (com.emc.storageos.svcs.errorhandling.resources.APIException)2 URI (java.net.URI)2 Date (java.util.Date)2 DecommissionedConstraint (com.emc.storageos.db.client.constraint.DecommissionedConstraint)1 StorageOSUserDAO (com.emc.storageos.db.client.model.StorageOSUserDAO)1 KeyCertificatePairGenerator (com.emc.storageos.security.keystore.impl.KeyCertificatePairGenerator)1 SecurityProvider (com.emc.storageos.security.keystore.impl.SecurityProvider)1 BadRequestException (com.emc.storageos.svcs.errorhandling.resources.BadRequestException)1 GeneralSecurityException (java.security.GeneralSecurityException)1 KeyStore (java.security.KeyStore)1 PrivateKeyEntry (java.security.KeyStore.PrivateKeyEntry)1 KeyStoreException (java.security.KeyStoreException)1